langchain 0.4.0.dev0__py3-none-any.whl → 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of langchain might be problematic. Click here for more details.
- langchain/__init__.py +2 -452
- langchain/agents/__init__.py +9 -178
- langchain/agents/factory.py +1582 -0
- langchain/agents/middleware/__init__.py +80 -0
- langchain/agents/middleware/_execution.py +388 -0
- langchain/agents/middleware/_redaction.py +350 -0
- langchain/agents/middleware/context_editing.py +274 -0
- langchain/agents/middleware/file_search.py +382 -0
- langchain/agents/middleware/human_in_the_loop.py +351 -0
- langchain/agents/middleware/model_call_limit.py +210 -0
- langchain/agents/middleware/model_fallback.py +137 -0
- langchain/agents/middleware/pii.py +317 -0
- langchain/agents/middleware/shell_tool.py +718 -0
- langchain/agents/middleware/summarization.py +249 -0
- langchain/agents/middleware/todo.py +219 -0
- langchain/agents/middleware/tool_call_limit.py +333 -0
- langchain/agents/middleware/tool_emulator.py +200 -0
- langchain/agents/middleware/tool_retry.py +384 -0
- langchain/agents/middleware/tool_selection.py +310 -0
- langchain/agents/middleware/types.py +1572 -0
- langchain/agents/structured_output.py +426 -0
- langchain/chat_models/__init__.py +7 -72
- langchain/chat_models/base.py +268 -358
- langchain/embeddings/__init__.py +7 -217
- langchain/embeddings/base.py +31 -43
- langchain/messages/__init__.py +72 -0
- langchain/rate_limiters/__init__.py +13 -0
- langchain/tools/__init__.py +17 -197
- langchain/tools/tool_node.py +1700 -0
- langchain-1.0.0.dist-info/METADATA +87 -0
- langchain-1.0.0.dist-info/RECORD +34 -0
- {langchain-0.4.0.dev0.dist-info → langchain-1.0.0.dist-info}/WHEEL +1 -1
- langchain/_api/__init__.py +0 -28
- langchain/_api/deprecation.py +0 -32
- langchain/_api/interactive_env.py +0 -5
- langchain/_api/module_import.py +0 -153
- langchain/_api/path.py +0 -3
- langchain/adapters/__init__.py +0 -0
- langchain/adapters/openai.py +0 -63
- langchain/agents/agent.py +0 -1824
- langchain/agents/agent_iterator.py +0 -438
- langchain/agents/agent_toolkits/__init__.py +0 -167
- langchain/agents/agent_toolkits/ainetwork/__init__.py +0 -1
- langchain/agents/agent_toolkits/ainetwork/toolkit.py +0 -25
- langchain/agents/agent_toolkits/amadeus/toolkit.py +0 -23
- langchain/agents/agent_toolkits/azure_cognitive_services.py +0 -29
- langchain/agents/agent_toolkits/base.py +0 -3
- langchain/agents/agent_toolkits/clickup/__init__.py +0 -0
- langchain/agents/agent_toolkits/clickup/toolkit.py +0 -25
- langchain/agents/agent_toolkits/conversational_retrieval/__init__.py +0 -0
- langchain/agents/agent_toolkits/conversational_retrieval/openai_functions.py +0 -87
- langchain/agents/agent_toolkits/conversational_retrieval/tool.py +0 -3
- langchain/agents/agent_toolkits/csv/__init__.py +0 -28
- langchain/agents/agent_toolkits/file_management/__init__.py +0 -31
- langchain/agents/agent_toolkits/file_management/toolkit.py +0 -29
- langchain/agents/agent_toolkits/github/__init__.py +0 -1
- langchain/agents/agent_toolkits/github/toolkit.py +0 -69
- langchain/agents/agent_toolkits/gitlab/__init__.py +0 -1
- langchain/agents/agent_toolkits/gitlab/toolkit.py +0 -25
- langchain/agents/agent_toolkits/gmail/__init__.py +0 -1
- langchain/agents/agent_toolkits/gmail/toolkit.py +0 -23
- langchain/agents/agent_toolkits/jira/__init__.py +0 -1
- langchain/agents/agent_toolkits/jira/toolkit.py +0 -23
- langchain/agents/agent_toolkits/json/__init__.py +0 -1
- langchain/agents/agent_toolkits/json/base.py +0 -25
- langchain/agents/agent_toolkits/json/prompt.py +0 -24
- langchain/agents/agent_toolkits/json/toolkit.py +0 -23
- langchain/agents/agent_toolkits/multion/__init__.py +0 -1
- langchain/agents/agent_toolkits/multion/toolkit.py +0 -25
- langchain/agents/agent_toolkits/nasa/__init__.py +0 -1
- langchain/agents/agent_toolkits/nasa/toolkit.py +0 -23
- langchain/agents/agent_toolkits/nla/__init__.py +0 -0
- langchain/agents/agent_toolkits/nla/tool.py +0 -23
- langchain/agents/agent_toolkits/nla/toolkit.py +0 -23
- langchain/agents/agent_toolkits/office365/__init__.py +0 -1
- langchain/agents/agent_toolkits/office365/toolkit.py +0 -25
- langchain/agents/agent_toolkits/openapi/__init__.py +0 -1
- langchain/agents/agent_toolkits/openapi/base.py +0 -25
- langchain/agents/agent_toolkits/openapi/planner.py +0 -52
- langchain/agents/agent_toolkits/openapi/planner_prompt.py +0 -103
- langchain/agents/agent_toolkits/openapi/prompt.py +0 -29
- langchain/agents/agent_toolkits/openapi/spec.py +0 -30
- langchain/agents/agent_toolkits/openapi/toolkit.py +0 -30
- langchain/agents/agent_toolkits/pandas/__init__.py +0 -28
- langchain/agents/agent_toolkits/playwright/__init__.py +0 -29
- langchain/agents/agent_toolkits/playwright/toolkit.py +0 -27
- langchain/agents/agent_toolkits/powerbi/__init__.py +0 -1
- langchain/agents/agent_toolkits/powerbi/base.py +0 -25
- langchain/agents/agent_toolkits/powerbi/chat_base.py +0 -27
- langchain/agents/agent_toolkits/powerbi/prompt.py +0 -36
- langchain/agents/agent_toolkits/powerbi/toolkit.py +0 -25
- langchain/agents/agent_toolkits/python/__init__.py +0 -28
- langchain/agents/agent_toolkits/slack/__init__.py +0 -1
- langchain/agents/agent_toolkits/slack/toolkit.py +0 -23
- langchain/agents/agent_toolkits/spark/__init__.py +0 -28
- langchain/agents/agent_toolkits/spark_sql/__init__.py +0 -1
- langchain/agents/agent_toolkits/spark_sql/base.py +0 -25
- langchain/agents/agent_toolkits/spark_sql/prompt.py +0 -27
- langchain/agents/agent_toolkits/spark_sql/toolkit.py +0 -25
- langchain/agents/agent_toolkits/sql/__init__.py +0 -1
- langchain/agents/agent_toolkits/sql/base.py +0 -23
- langchain/agents/agent_toolkits/sql/prompt.py +0 -29
- langchain/agents/agent_toolkits/sql/toolkit.py +0 -25
- langchain/agents/agent_toolkits/steam/__init__.py +0 -1
- langchain/agents/agent_toolkits/steam/toolkit.py +0 -23
- langchain/agents/agent_toolkits/vectorstore/__init__.py +0 -1
- langchain/agents/agent_toolkits/vectorstore/base.py +0 -219
- langchain/agents/agent_toolkits/vectorstore/prompt.py +0 -11
- langchain/agents/agent_toolkits/vectorstore/toolkit.py +0 -97
- langchain/agents/agent_toolkits/xorbits/__init__.py +0 -28
- langchain/agents/agent_toolkits/zapier/__init__.py +0 -1
- langchain/agents/agent_toolkits/zapier/toolkit.py +0 -25
- langchain/agents/agent_types.py +0 -57
- langchain/agents/chat/__init__.py +0 -0
- langchain/agents/chat/base.py +0 -180
- langchain/agents/chat/output_parser.py +0 -74
- langchain/agents/chat/prompt.py +0 -29
- langchain/agents/conversational/__init__.py +0 -1
- langchain/agents/conversational/base.py +0 -178
- langchain/agents/conversational/output_parser.py +0 -51
- langchain/agents/conversational/prompt.py +0 -35
- langchain/agents/conversational_chat/__init__.py +0 -1
- langchain/agents/conversational_chat/base.py +0 -183
- langchain/agents/conversational_chat/output_parser.py +0 -57
- langchain/agents/conversational_chat/prompt.py +0 -56
- langchain/agents/format_scratchpad/__init__.py +0 -25
- langchain/agents/format_scratchpad/log.py +0 -25
- langchain/agents/format_scratchpad/log_to_messages.py +0 -26
- langchain/agents/format_scratchpad/openai_functions.py +0 -80
- langchain/agents/format_scratchpad/openai_tools.py +0 -5
- langchain/agents/format_scratchpad/tools.py +0 -65
- langchain/agents/format_scratchpad/xml.py +0 -52
- langchain/agents/initialize.py +0 -105
- langchain/agents/json_chat/__init__.py +0 -0
- langchain/agents/json_chat/base.py +0 -196
- langchain/agents/json_chat/prompt.py +0 -8
- langchain/agents/load_tools.py +0 -13
- langchain/agents/loading.py +0 -148
- langchain/agents/mrkl/__init__.py +0 -1
- langchain/agents/mrkl/base.py +0 -218
- langchain/agents/mrkl/output_parser.py +0 -103
- langchain/agents/mrkl/prompt.py +0 -15
- langchain/agents/openai_assistant/__init__.py +0 -3
- langchain/agents/openai_assistant/base.py +0 -818
- langchain/agents/openai_functions_agent/__init__.py +0 -0
- langchain/agents/openai_functions_agent/agent_token_buffer_memory.py +0 -103
- langchain/agents/openai_functions_agent/base.py +0 -382
- langchain/agents/openai_functions_multi_agent/__init__.py +0 -0
- langchain/agents/openai_functions_multi_agent/base.py +0 -337
- langchain/agents/openai_tools/__init__.py +0 -0
- langchain/agents/openai_tools/base.py +0 -109
- langchain/agents/output_parsers/__init__.py +0 -35
- langchain/agents/output_parsers/json.py +0 -64
- langchain/agents/output_parsers/openai_functions.py +0 -103
- langchain/agents/output_parsers/openai_tools.py +0 -77
- langchain/agents/output_parsers/react_json_single_input.py +0 -87
- langchain/agents/output_parsers/react_single_input.py +0 -102
- langchain/agents/output_parsers/self_ask.py +0 -53
- langchain/agents/output_parsers/tools.py +0 -121
- langchain/agents/output_parsers/xml.py +0 -126
- langchain/agents/react/__init__.py +0 -1
- langchain/agents/react/agent.py +0 -145
- langchain/agents/react/base.py +0 -189
- langchain/agents/react/output_parser.py +0 -35
- langchain/agents/react/textworld_prompt.py +0 -51
- langchain/agents/react/wiki_prompt.py +0 -70
- langchain/agents/schema.py +0 -37
- langchain/agents/self_ask_with_search/__init__.py +0 -4
- langchain/agents/self_ask_with_search/base.py +0 -219
- langchain/agents/self_ask_with_search/output_parser.py +0 -4
- langchain/agents/self_ask_with_search/prompt.py +0 -43
- langchain/agents/structured_chat/__init__.py +0 -0
- langchain/agents/structured_chat/base.py +0 -309
- langchain/agents/structured_chat/output_parser.py +0 -112
- langchain/agents/structured_chat/prompt.py +0 -34
- langchain/agents/tool_calling_agent/__init__.py +0 -0
- langchain/agents/tool_calling_agent/base.py +0 -111
- langchain/agents/tools.py +0 -50
- langchain/agents/types.py +0 -27
- langchain/agents/utils.py +0 -19
- langchain/agents/xml/__init__.py +0 -0
- langchain/agents/xml/base.py +0 -237
- langchain/agents/xml/prompt.py +0 -21
- langchain/base_language.py +0 -7
- langchain/cache.py +0 -72
- langchain/callbacks/__init__.py +0 -139
- langchain/callbacks/aim_callback.py +0 -33
- langchain/callbacks/argilla_callback.py +0 -25
- langchain/callbacks/arize_callback.py +0 -25
- langchain/callbacks/arthur_callback.py +0 -25
- langchain/callbacks/base.py +0 -29
- langchain/callbacks/clearml_callback.py +0 -25
- langchain/callbacks/comet_ml_callback.py +0 -25
- langchain/callbacks/confident_callback.py +0 -25
- langchain/callbacks/context_callback.py +0 -25
- langchain/callbacks/file.py +0 -3
- langchain/callbacks/flyte_callback.py +0 -25
- langchain/callbacks/human.py +0 -33
- langchain/callbacks/infino_callback.py +0 -25
- langchain/callbacks/labelstudio_callback.py +0 -33
- langchain/callbacks/llmonitor_callback.py +0 -27
- langchain/callbacks/manager.py +0 -89
- langchain/callbacks/mlflow_callback.py +0 -38
- langchain/callbacks/openai_info.py +0 -25
- langchain/callbacks/promptlayer_callback.py +0 -27
- langchain/callbacks/sagemaker_callback.py +0 -27
- langchain/callbacks/stdout.py +0 -3
- langchain/callbacks/streaming_aiter.py +0 -86
- langchain/callbacks/streaming_aiter_final_only.py +0 -100
- langchain/callbacks/streaming_stdout.py +0 -5
- langchain/callbacks/streaming_stdout_final_only.py +0 -96
- langchain/callbacks/streamlit/__init__.py +0 -86
- langchain/callbacks/streamlit/mutable_expander.py +0 -33
- langchain/callbacks/streamlit/streamlit_callback_handler.py +0 -49
- langchain/callbacks/tracers/__init__.py +0 -38
- langchain/callbacks/tracers/base.py +0 -6
- langchain/callbacks/tracers/comet.py +0 -30
- langchain/callbacks/tracers/evaluation.py +0 -8
- langchain/callbacks/tracers/langchain.py +0 -8
- langchain/callbacks/tracers/langchain_v1.py +0 -3
- langchain/callbacks/tracers/log_stream.py +0 -9
- langchain/callbacks/tracers/logging.py +0 -57
- langchain/callbacks/tracers/root_listeners.py +0 -3
- langchain/callbacks/tracers/run_collector.py +0 -3
- langchain/callbacks/tracers/schemas.py +0 -27
- langchain/callbacks/tracers/stdout.py +0 -6
- langchain/callbacks/tracers/wandb.py +0 -27
- langchain/callbacks/trubrics_callback.py +0 -25
- langchain/callbacks/utils.py +0 -48
- langchain/callbacks/wandb_callback.py +0 -25
- langchain/callbacks/whylabs_callback.py +0 -25
- langchain/chains/__init__.py +0 -96
- langchain/chains/api/__init__.py +0 -1
- langchain/chains/api/base.py +0 -398
- langchain/chains/api/news_docs.py +0 -31
- langchain/chains/api/open_meteo_docs.py +0 -32
- langchain/chains/api/openapi/__init__.py +0 -0
- langchain/chains/api/openapi/chain.py +0 -23
- langchain/chains/api/openapi/prompts.py +0 -27
- langchain/chains/api/openapi/requests_chain.py +0 -29
- langchain/chains/api/openapi/response_chain.py +0 -29
- langchain/chains/api/podcast_docs.py +0 -27
- langchain/chains/api/prompt.py +0 -35
- langchain/chains/api/tmdb_docs.py +0 -36
- langchain/chains/base.py +0 -806
- langchain/chains/chat_vector_db/__init__.py +0 -0
- langchain/chains/chat_vector_db/prompts.py +0 -19
- langchain/chains/combine_documents/__init__.py +0 -15
- langchain/chains/combine_documents/base.py +0 -293
- langchain/chains/combine_documents/map_reduce.py +0 -303
- langchain/chains/combine_documents/map_rerank.py +0 -249
- langchain/chains/combine_documents/reduce.py +0 -382
- langchain/chains/combine_documents/refine.py +0 -237
- langchain/chains/combine_documents/stuff.py +0 -292
- langchain/chains/constitutional_ai/__init__.py +0 -2
- langchain/chains/constitutional_ai/base.py +0 -328
- langchain/chains/constitutional_ai/models.py +0 -11
- langchain/chains/constitutional_ai/principles.py +0 -278
- langchain/chains/constitutional_ai/prompts.py +0 -120
- langchain/chains/conversation/__init__.py +0 -1
- langchain/chains/conversation/base.py +0 -146
- langchain/chains/conversation/memory.py +0 -45
- langchain/chains/conversation/prompt.py +0 -28
- langchain/chains/conversational_retrieval/__init__.py +0 -1
- langchain/chains/conversational_retrieval/base.py +0 -576
- langchain/chains/conversational_retrieval/prompts.py +0 -19
- langchain/chains/elasticsearch_database/__init__.py +0 -3
- langchain/chains/elasticsearch_database/base.py +0 -212
- langchain/chains/elasticsearch_database/prompts.py +0 -35
- langchain/chains/ernie_functions/__init__.py +0 -44
- langchain/chains/ernie_functions/base.py +0 -49
- langchain/chains/example_generator.py +0 -22
- langchain/chains/flare/__init__.py +0 -1
- langchain/chains/flare/base.py +0 -284
- langchain/chains/flare/prompts.py +0 -46
- langchain/chains/graph_qa/__init__.py +0 -0
- langchain/chains/graph_qa/arangodb.py +0 -23
- langchain/chains/graph_qa/base.py +0 -23
- langchain/chains/graph_qa/cypher.py +0 -39
- langchain/chains/graph_qa/cypher_utils.py +0 -27
- langchain/chains/graph_qa/falkordb.py +0 -29
- langchain/chains/graph_qa/gremlin.py +0 -36
- langchain/chains/graph_qa/hugegraph.py +0 -23
- langchain/chains/graph_qa/kuzu.py +0 -29
- langchain/chains/graph_qa/nebulagraph.py +0 -23
- langchain/chains/graph_qa/neptune_cypher.py +0 -39
- langchain/chains/graph_qa/neptune_sparql.py +0 -36
- langchain/chains/graph_qa/ontotext_graphdb.py +0 -25
- langchain/chains/graph_qa/prompts.py +0 -96
- langchain/chains/graph_qa/sparql.py +0 -23
- langchain/chains/history_aware_retriever.py +0 -68
- langchain/chains/hyde/__init__.py +0 -4
- langchain/chains/hyde/base.py +0 -124
- langchain/chains/hyde/prompts.py +0 -46
- langchain/chains/llm.py +0 -447
- langchain/chains/llm_bash/__init__.py +0 -10
- langchain/chains/llm_checker/__init__.py +0 -4
- langchain/chains/llm_checker/base.py +0 -205
- langchain/chains/llm_checker/prompt.py +0 -30
- langchain/chains/llm_math/__init__.py +0 -4
- langchain/chains/llm_math/base.py +0 -319
- langchain/chains/llm_math/prompt.py +0 -43
- langchain/chains/llm_requests.py +0 -23
- langchain/chains/llm_summarization_checker/__init__.py +0 -7
- langchain/chains/llm_summarization_checker/base.py +0 -217
- langchain/chains/llm_summarization_checker/prompts/are_all_true_prompt.txt +0 -38
- langchain/chains/llm_summarization_checker/prompts/check_facts.txt +0 -10
- langchain/chains/llm_summarization_checker/prompts/create_facts.txt +0 -10
- langchain/chains/llm_summarization_checker/prompts/revise_summary.txt +0 -17
- langchain/chains/llm_symbolic_math/__init__.py +0 -10
- langchain/chains/loading.py +0 -734
- langchain/chains/mapreduce.py +0 -121
- langchain/chains/moderation.py +0 -135
- langchain/chains/natbot/__init__.py +0 -4
- langchain/chains/natbot/base.py +0 -165
- langchain/chains/natbot/crawler.py +0 -472
- langchain/chains/natbot/prompt.py +0 -143
- langchain/chains/openai_functions/__init__.py +0 -44
- langchain/chains/openai_functions/base.py +0 -237
- langchain/chains/openai_functions/citation_fuzzy_match.py +0 -169
- langchain/chains/openai_functions/extraction.py +0 -197
- langchain/chains/openai_functions/openapi.py +0 -409
- langchain/chains/openai_functions/qa_with_structure.py +0 -142
- langchain/chains/openai_functions/tagging.py +0 -174
- langchain/chains/openai_functions/utils.py +0 -40
- langchain/chains/openai_tools/__init__.py +0 -3
- langchain/chains/openai_tools/extraction.py +0 -79
- langchain/chains/prompt_selector.py +0 -65
- langchain/chains/qa_generation/__init__.py +0 -0
- langchain/chains/qa_generation/base.py +0 -128
- langchain/chains/qa_generation/prompt.py +0 -50
- langchain/chains/qa_with_sources/__init__.py +0 -5
- langchain/chains/qa_with_sources/base.py +0 -266
- langchain/chains/qa_with_sources/loading.py +0 -209
- langchain/chains/qa_with_sources/map_reduce_prompt.py +0 -54
- langchain/chains/qa_with_sources/refine_prompts.py +0 -37
- langchain/chains/qa_with_sources/retrieval.py +0 -75
- langchain/chains/qa_with_sources/stuff_prompt.py +0 -43
- langchain/chains/qa_with_sources/vector_db.py +0 -88
- langchain/chains/query_constructor/__init__.py +0 -3
- langchain/chains/query_constructor/base.py +0 -378
- langchain/chains/query_constructor/ir.py +0 -23
- langchain/chains/query_constructor/parser.py +0 -272
- langchain/chains/query_constructor/prompt.py +0 -226
- langchain/chains/query_constructor/schema.py +0 -14
- langchain/chains/question_answering/__init__.py +0 -6
- langchain/chains/question_answering/chain.py +0 -279
- langchain/chains/question_answering/map_reduce_prompt.py +0 -80
- langchain/chains/question_answering/map_rerank_prompt.py +0 -66
- langchain/chains/question_answering/refine_prompts.py +0 -72
- langchain/chains/question_answering/stuff_prompt.py +0 -33
- langchain/chains/retrieval.py +0 -67
- langchain/chains/retrieval_qa/__init__.py +0 -1
- langchain/chains/retrieval_qa/base.py +0 -374
- langchain/chains/retrieval_qa/prompt.py +0 -11
- langchain/chains/router/__init__.py +0 -12
- langchain/chains/router/base.py +0 -154
- langchain/chains/router/embedding_router.py +0 -96
- langchain/chains/router/llm_router.py +0 -198
- langchain/chains/router/multi_prompt.py +0 -184
- langchain/chains/router/multi_prompt_prompt.py +0 -32
- langchain/chains/router/multi_retrieval_prompt.py +0 -30
- langchain/chains/router/multi_retrieval_qa.py +0 -127
- langchain/chains/sequential.py +0 -220
- langchain/chains/sql_database/__init__.py +0 -1
- langchain/chains/sql_database/prompt.py +0 -282
- langchain/chains/sql_database/query.py +0 -167
- langchain/chains/structured_output/__init__.py +0 -6
- langchain/chains/structured_output/base.py +0 -584
- langchain/chains/summarize/__init__.py +0 -6
- langchain/chains/summarize/chain.py +0 -174
- langchain/chains/summarize/map_reduce_prompt.py +0 -10
- langchain/chains/summarize/refine_prompts.py +0 -23
- langchain/chains/summarize/stuff_prompt.py +0 -10
- langchain/chains/transform.py +0 -88
- langchain/chat_loaders/__init__.py +0 -19
- langchain/chat_loaders/base.py +0 -3
- langchain/chat_loaders/facebook_messenger.py +0 -32
- langchain/chat_loaders/gmail.py +0 -23
- langchain/chat_loaders/imessage.py +0 -23
- langchain/chat_loaders/langsmith.py +0 -30
- langchain/chat_loaders/slack.py +0 -23
- langchain/chat_loaders/telegram.py +0 -23
- langchain/chat_loaders/utils.py +0 -36
- langchain/chat_loaders/whatsapp.py +0 -23
- langchain/chat_models/anthropic.py +0 -30
- langchain/chat_models/anyscale.py +0 -23
- langchain/chat_models/azure_openai.py +0 -23
- langchain/chat_models/azureml_endpoint.py +0 -30
- langchain/chat_models/baichuan.py +0 -23
- langchain/chat_models/baidu_qianfan_endpoint.py +0 -27
- langchain/chat_models/bedrock.py +0 -27
- langchain/chat_models/cohere.py +0 -23
- langchain/chat_models/databricks.py +0 -23
- langchain/chat_models/ernie.py +0 -23
- langchain/chat_models/everlyai.py +0 -23
- langchain/chat_models/fake.py +0 -30
- langchain/chat_models/fireworks.py +0 -23
- langchain/chat_models/gigachat.py +0 -23
- langchain/chat_models/google_palm.py +0 -30
- langchain/chat_models/human.py +0 -23
- langchain/chat_models/hunyuan.py +0 -23
- langchain/chat_models/javelin_ai_gateway.py +0 -30
- langchain/chat_models/jinachat.py +0 -23
- langchain/chat_models/konko.py +0 -23
- langchain/chat_models/litellm.py +0 -30
- langchain/chat_models/meta.py +0 -25
- langchain/chat_models/minimax.py +0 -23
- langchain/chat_models/mlflow.py +0 -23
- langchain/chat_models/mlflow_ai_gateway.py +0 -30
- langchain/chat_models/ollama.py +0 -23
- langchain/chat_models/openai.py +0 -23
- langchain/chat_models/pai_eas_endpoint.py +0 -25
- langchain/chat_models/promptlayer_openai.py +0 -25
- langchain/chat_models/tongyi.py +0 -23
- langchain/chat_models/vertexai.py +0 -23
- langchain/chat_models/volcengine_maas.py +0 -30
- langchain/chat_models/yandex.py +0 -23
- langchain/docstore/__init__.py +0 -48
- langchain/docstore/arbitrary_fn.py +0 -23
- langchain/docstore/base.py +0 -27
- langchain/docstore/document.py +0 -3
- langchain/docstore/in_memory.py +0 -23
- langchain/docstore/wikipedia.py +0 -23
- langchain/document_loaders/__init__.py +0 -553
- langchain/document_loaders/acreom.py +0 -23
- langchain/document_loaders/airbyte.py +0 -48
- langchain/document_loaders/airbyte_json.py +0 -23
- langchain/document_loaders/airtable.py +0 -23
- langchain/document_loaders/apify_dataset.py +0 -23
- langchain/document_loaders/arcgis_loader.py +0 -23
- langchain/document_loaders/arxiv.py +0 -23
- langchain/document_loaders/assemblyai.py +0 -28
- langchain/document_loaders/async_html.py +0 -23
- langchain/document_loaders/azlyrics.py +0 -23
- langchain/document_loaders/azure_ai_data.py +0 -23
- langchain/document_loaders/azure_blob_storage_container.py +0 -25
- langchain/document_loaders/azure_blob_storage_file.py +0 -25
- langchain/document_loaders/baiducloud_bos_directory.py +0 -29
- langchain/document_loaders/baiducloud_bos_file.py +0 -27
- langchain/document_loaders/base.py +0 -3
- langchain/document_loaders/base_o365.py +0 -23
- langchain/document_loaders/bibtex.py +0 -23
- langchain/document_loaders/bigquery.py +0 -23
- langchain/document_loaders/bilibili.py +0 -23
- langchain/document_loaders/blackboard.py +0 -23
- langchain/document_loaders/blob_loaders/__init__.py +0 -36
- langchain/document_loaders/blob_loaders/file_system.py +0 -23
- langchain/document_loaders/blob_loaders/schema.py +0 -26
- langchain/document_loaders/blob_loaders/youtube_audio.py +0 -23
- langchain/document_loaders/blockchain.py +0 -28
- langchain/document_loaders/brave_search.py +0 -23
- langchain/document_loaders/browserless.py +0 -23
- langchain/document_loaders/chatgpt.py +0 -28
- langchain/document_loaders/chromium.py +0 -23
- langchain/document_loaders/college_confidential.py +0 -25
- langchain/document_loaders/concurrent.py +0 -23
- langchain/document_loaders/confluence.py +0 -28
- langchain/document_loaders/conllu.py +0 -23
- langchain/document_loaders/couchbase.py +0 -23
- langchain/document_loaders/csv_loader.py +0 -27
- langchain/document_loaders/cube_semantic.py +0 -23
- langchain/document_loaders/datadog_logs.py +0 -23
- langchain/document_loaders/dataframe.py +0 -28
- langchain/document_loaders/diffbot.py +0 -23
- langchain/document_loaders/directory.py +0 -23
- langchain/document_loaders/discord.py +0 -23
- langchain/document_loaders/docugami.py +0 -23
- langchain/document_loaders/docusaurus.py +0 -23
- langchain/document_loaders/dropbox.py +0 -23
- langchain/document_loaders/duckdb_loader.py +0 -23
- langchain/document_loaders/email.py +0 -30
- langchain/document_loaders/epub.py +0 -23
- langchain/document_loaders/etherscan.py +0 -23
- langchain/document_loaders/evernote.py +0 -23
- langchain/document_loaders/excel.py +0 -23
- langchain/document_loaders/facebook_chat.py +0 -28
- langchain/document_loaders/fauna.py +0 -23
- langchain/document_loaders/figma.py +0 -23
- langchain/document_loaders/gcs_directory.py +0 -23
- langchain/document_loaders/gcs_file.py +0 -23
- langchain/document_loaders/generic.py +0 -23
- langchain/document_loaders/geodataframe.py +0 -23
- langchain/document_loaders/git.py +0 -23
- langchain/document_loaders/gitbook.py +0 -23
- langchain/document_loaders/github.py +0 -28
- langchain/document_loaders/google_speech_to_text.py +0 -23
- langchain/document_loaders/googledrive.py +0 -23
- langchain/document_loaders/gutenberg.py +0 -23
- langchain/document_loaders/helpers.py +0 -30
- langchain/document_loaders/hn.py +0 -23
- langchain/document_loaders/html.py +0 -23
- langchain/document_loaders/html_bs.py +0 -23
- langchain/document_loaders/hugging_face_dataset.py +0 -23
- langchain/document_loaders/ifixit.py +0 -23
- langchain/document_loaders/image.py +0 -23
- langchain/document_loaders/image_captions.py +0 -23
- langchain/document_loaders/imsdb.py +0 -23
- langchain/document_loaders/iugu.py +0 -23
- langchain/document_loaders/joplin.py +0 -23
- langchain/document_loaders/json_loader.py +0 -23
- langchain/document_loaders/lakefs.py +0 -33
- langchain/document_loaders/larksuite.py +0 -23
- langchain/document_loaders/markdown.py +0 -25
- langchain/document_loaders/mastodon.py +0 -23
- langchain/document_loaders/max_compute.py +0 -23
- langchain/document_loaders/mediawikidump.py +0 -23
- langchain/document_loaders/merge.py +0 -23
- langchain/document_loaders/mhtml.py +0 -23
- langchain/document_loaders/modern_treasury.py +0 -23
- langchain/document_loaders/mongodb.py +0 -23
- langchain/document_loaders/news.py +0 -23
- langchain/document_loaders/notebook.py +0 -33
- langchain/document_loaders/notion.py +0 -23
- langchain/document_loaders/notiondb.py +0 -23
- langchain/document_loaders/nuclia.py +0 -23
- langchain/document_loaders/obs_directory.py +0 -23
- langchain/document_loaders/obs_file.py +0 -23
- langchain/document_loaders/obsidian.py +0 -23
- langchain/document_loaders/odt.py +0 -23
- langchain/document_loaders/onedrive.py +0 -23
- langchain/document_loaders/onedrive_file.py +0 -23
- langchain/document_loaders/onenote.py +0 -23
- langchain/document_loaders/open_city_data.py +0 -23
- langchain/document_loaders/org_mode.py +0 -25
- langchain/document_loaders/parsers/__init__.py +0 -58
- langchain/document_loaders/parsers/audio.py +0 -33
- langchain/document_loaders/parsers/docai.py +0 -30
- langchain/document_loaders/parsers/generic.py +0 -25
- langchain/document_loaders/parsers/grobid.py +0 -30
- langchain/document_loaders/parsers/html/__init__.py +0 -25
- langchain/document_loaders/parsers/html/bs4.py +0 -25
- langchain/document_loaders/parsers/language/__init__.py +0 -29
- langchain/document_loaders/parsers/language/cobol.py +0 -27
- langchain/document_loaders/parsers/language/code_segmenter.py +0 -29
- langchain/document_loaders/parsers/language/javascript.py +0 -29
- langchain/document_loaders/parsers/language/language_parser.py +0 -29
- langchain/document_loaders/parsers/language/python.py +0 -27
- langchain/document_loaders/parsers/msword.py +0 -25
- langchain/document_loaders/parsers/pdf.py +0 -50
- langchain/document_loaders/parsers/registry.py +0 -25
- langchain/document_loaders/parsers/txt.py +0 -23
- langchain/document_loaders/pdf.py +0 -65
- langchain/document_loaders/polars_dataframe.py +0 -23
- langchain/document_loaders/powerpoint.py +0 -25
- langchain/document_loaders/psychic.py +0 -23
- langchain/document_loaders/pubmed.py +0 -23
- langchain/document_loaders/pyspark_dataframe.py +0 -26
- langchain/document_loaders/python.py +0 -22
- langchain/document_loaders/quip.py +0 -23
- langchain/document_loaders/readthedocs.py +0 -23
- langchain/document_loaders/recursive_url_loader.py +0 -23
- langchain/document_loaders/reddit.py +0 -23
- langchain/document_loaders/roam.py +0 -23
- langchain/document_loaders/rocksetdb.py +0 -23
- langchain/document_loaders/rspace.py +0 -23
- langchain/document_loaders/rss.py +0 -23
- langchain/document_loaders/rst.py +0 -23
- langchain/document_loaders/rtf.py +0 -23
- langchain/document_loaders/s3_directory.py +0 -23
- langchain/document_loaders/s3_file.py +0 -23
- langchain/document_loaders/sharepoint.py +0 -23
- langchain/document_loaders/sitemap.py +0 -23
- langchain/document_loaders/slack_directory.py +0 -23
- langchain/document_loaders/snowflake_loader.py +0 -23
- langchain/document_loaders/spreedly.py +0 -23
- langchain/document_loaders/srt.py +0 -23
- langchain/document_loaders/stripe.py +0 -23
- langchain/document_loaders/telegram.py +0 -38
- langchain/document_loaders/tencent_cos_directory.py +0 -25
- langchain/document_loaders/tencent_cos_file.py +0 -23
- langchain/document_loaders/tensorflow_datasets.py +0 -23
- langchain/document_loaders/text.py +0 -23
- langchain/document_loaders/tomarkdown.py +0 -23
- langchain/document_loaders/toml.py +0 -23
- langchain/document_loaders/trello.py +0 -23
- langchain/document_loaders/tsv.py +0 -23
- langchain/document_loaders/twitter.py +0 -23
- langchain/document_loaders/unstructured.py +0 -54
- langchain/document_loaders/url.py +0 -23
- langchain/document_loaders/url_playwright.py +0 -33
- langchain/document_loaders/url_selenium.py +0 -23
- langchain/document_loaders/weather.py +0 -23
- langchain/document_loaders/web_base.py +0 -23
- langchain/document_loaders/whatsapp_chat.py +0 -28
- langchain/document_loaders/wikipedia.py +0 -23
- langchain/document_loaders/word_document.py +0 -30
- langchain/document_loaders/xml.py +0 -23
- langchain/document_loaders/xorbits.py +0 -23
- langchain/document_loaders/youtube.py +0 -33
- langchain/document_transformers/__init__.py +0 -77
- langchain/document_transformers/beautiful_soup_transformer.py +0 -25
- langchain/document_transformers/doctran_text_extract.py +0 -25
- langchain/document_transformers/doctran_text_qa.py +0 -25
- langchain/document_transformers/doctran_text_translate.py +0 -25
- langchain/document_transformers/embeddings_redundant_filter.py +0 -50
- langchain/document_transformers/google_translate.py +0 -25
- langchain/document_transformers/html2text.py +0 -25
- langchain/document_transformers/long_context_reorder.py +0 -23
- langchain/document_transformers/nuclia_text_transform.py +0 -25
- langchain/document_transformers/openai_functions.py +0 -32
- langchain/document_transformers/xsl/html_chunks_with_headers.xslt +0 -199
- langchain/embeddings/aleph_alpha.py +0 -30
- langchain/embeddings/awa.py +0 -23
- langchain/embeddings/azure_openai.py +0 -23
- langchain/embeddings/baidu_qianfan_endpoint.py +0 -23
- langchain/embeddings/bedrock.py +0 -23
- langchain/embeddings/bookend.py +0 -23
- langchain/embeddings/cache.py +0 -368
- langchain/embeddings/clarifai.py +0 -23
- langchain/embeddings/cloudflare_workersai.py +0 -29
- langchain/embeddings/cohere.py +0 -23
- langchain/embeddings/dashscope.py +0 -23
- langchain/embeddings/databricks.py +0 -23
- langchain/embeddings/deepinfra.py +0 -23
- langchain/embeddings/edenai.py +0 -23
- langchain/embeddings/elasticsearch.py +0 -23
- langchain/embeddings/embaas.py +0 -23
- langchain/embeddings/ernie.py +0 -23
- langchain/embeddings/fake.py +0 -30
- langchain/embeddings/fastembed.py +0 -23
- langchain/embeddings/google_palm.py +0 -23
- langchain/embeddings/gpt4all.py +0 -23
- langchain/embeddings/gradient_ai.py +0 -23
- langchain/embeddings/huggingface.py +0 -36
- langchain/embeddings/huggingface_hub.py +0 -23
- langchain/embeddings/infinity.py +0 -30
- langchain/embeddings/javelin_ai_gateway.py +0 -23
- langchain/embeddings/jina.py +0 -23
- langchain/embeddings/johnsnowlabs.py +0 -23
- langchain/embeddings/llamacpp.py +0 -23
- langchain/embeddings/llm_rails.py +0 -23
- langchain/embeddings/localai.py +0 -23
- langchain/embeddings/minimax.py +0 -23
- langchain/embeddings/mlflow.py +0 -23
- langchain/embeddings/mlflow_gateway.py +0 -23
- langchain/embeddings/modelscope_hub.py +0 -23
- langchain/embeddings/mosaicml.py +0 -23
- langchain/embeddings/nlpcloud.py +0 -23
- langchain/embeddings/octoai_embeddings.py +0 -23
- langchain/embeddings/ollama.py +0 -23
- langchain/embeddings/openai.py +0 -23
- langchain/embeddings/sagemaker_endpoint.py +0 -30
- langchain/embeddings/self_hosted.py +0 -23
- langchain/embeddings/self_hosted_hugging_face.py +0 -30
- langchain/embeddings/sentence_transformer.py +0 -21
- langchain/embeddings/spacy_embeddings.py +0 -23
- langchain/embeddings/tensorflow_hub.py +0 -23
- langchain/embeddings/vertexai.py +0 -23
- langchain/embeddings/voyageai.py +0 -23
- langchain/embeddings/xinference.py +0 -23
- langchain/env.py +0 -17
- langchain/evaluation/__init__.py +0 -128
- langchain/evaluation/agents/__init__.py +0 -5
- langchain/evaluation/agents/trajectory_eval_chain.py +0 -416
- langchain/evaluation/agents/trajectory_eval_prompt.py +0 -146
- langchain/evaluation/comparison/__init__.py +0 -36
- langchain/evaluation/comparison/eval_chain.py +0 -462
- langchain/evaluation/comparison/prompt.py +0 -59
- langchain/evaluation/criteria/__init__.py +0 -56
- langchain/evaluation/criteria/eval_chain.py +0 -606
- langchain/evaluation/criteria/prompt.py +0 -37
- langchain/evaluation/embedding_distance/__init__.py +0 -13
- langchain/evaluation/embedding_distance/base.py +0 -613
- langchain/evaluation/exact_match/__init__.py +0 -0
- langchain/evaluation/exact_match/base.py +0 -110
- langchain/evaluation/loading.py +0 -207
- langchain/evaluation/parsing/__init__.py +0 -0
- langchain/evaluation/parsing/base.py +0 -175
- langchain/evaluation/parsing/json_distance.py +0 -108
- langchain/evaluation/parsing/json_schema.py +0 -97
- langchain/evaluation/qa/__init__.py +0 -10
- langchain/evaluation/qa/eval_chain.py +0 -372
- langchain/evaluation/qa/eval_prompt.py +0 -78
- langchain/evaluation/qa/generate_chain.py +0 -36
- langchain/evaluation/qa/generate_prompt.py +0 -21
- langchain/evaluation/regex_match/__init__.py +0 -0
- langchain/evaluation/regex_match/base.py +0 -94
- langchain/evaluation/schema.py +0 -491
- langchain/evaluation/scoring/__init__.py +0 -31
- langchain/evaluation/scoring/eval_chain.py +0 -476
- langchain/evaluation/scoring/prompt.py +0 -53
- langchain/evaluation/string_distance/__init__.py +0 -13
- langchain/evaluation/string_distance/base.py +0 -472
- langchain/example_generator.py +0 -5
- langchain/formatting.py +0 -5
- langchain/globals.py +0 -180
- langchain/graphs/__init__.py +0 -57
- langchain/graphs/arangodb_graph.py +0 -28
- langchain/graphs/falkordb_graph.py +0 -23
- langchain/graphs/graph_document.py +0 -33
- langchain/graphs/graph_store.py +0 -23
- langchain/graphs/hugegraph.py +0 -23
- langchain/graphs/kuzu_graph.py +0 -23
- langchain/graphs/memgraph_graph.py +0 -23
- langchain/graphs/nebula_graph.py +0 -23
- langchain/graphs/neo4j_graph.py +0 -23
- langchain/graphs/neptune_graph.py +0 -23
- langchain/graphs/networkx_graph.py +0 -36
- langchain/graphs/rdf_graph.py +0 -23
- langchain/hub.py +0 -131
- langchain/indexes/__init__.py +0 -50
- langchain/indexes/_api.py +0 -5
- langchain/indexes/_sql_record_manager.py +0 -539
- langchain/indexes/graph.py +0 -28
- langchain/indexes/prompts/__init__.py +0 -13
- langchain/indexes/prompts/entity_extraction.py +0 -39
- langchain/indexes/prompts/entity_summarization.py +0 -24
- langchain/indexes/prompts/knowledge_triplet_extraction.py +0 -36
- langchain/indexes/vectorstore.py +0 -269
- langchain/input.py +0 -15
- langchain/llms/__init__.py +0 -734
- langchain/llms/ai21.py +0 -28
- langchain/llms/aleph_alpha.py +0 -23
- langchain/llms/amazon_api_gateway.py +0 -23
- langchain/llms/anthropic.py +0 -23
- langchain/llms/anyscale.py +0 -23
- langchain/llms/arcee.py +0 -23
- langchain/llms/aviary.py +0 -23
- langchain/llms/azureml_endpoint.py +0 -48
- langchain/llms/baidu_qianfan_endpoint.py +0 -23
- langchain/llms/bananadev.py +0 -23
- langchain/llms/base.py +0 -20
- langchain/llms/baseten.py +0 -23
- langchain/llms/beam.py +0 -23
- langchain/llms/bedrock.py +0 -28
- langchain/llms/bittensor.py +0 -23
- langchain/llms/cerebriumai.py +0 -23
- langchain/llms/chatglm.py +0 -23
- langchain/llms/clarifai.py +0 -23
- langchain/llms/cloudflare_workersai.py +0 -25
- langchain/llms/cohere.py +0 -23
- langchain/llms/ctransformers.py +0 -23
- langchain/llms/ctranslate2.py +0 -23
- langchain/llms/databricks.py +0 -23
- langchain/llms/deepinfra.py +0 -23
- langchain/llms/deepsparse.py +0 -23
- langchain/llms/edenai.py +0 -23
- langchain/llms/fake.py +0 -28
- langchain/llms/fireworks.py +0 -23
- langchain/llms/forefrontai.py +0 -23
- langchain/llms/gigachat.py +0 -23
- langchain/llms/google_palm.py +0 -23
- langchain/llms/gooseai.py +0 -23
- langchain/llms/gpt4all.py +0 -23
- langchain/llms/gradient_ai.py +0 -28
- langchain/llms/grammars/json.gbnf +0 -29
- langchain/llms/grammars/list.gbnf +0 -14
- langchain/llms/huggingface_endpoint.py +0 -23
- langchain/llms/huggingface_hub.py +0 -23
- langchain/llms/huggingface_pipeline.py +0 -23
- langchain/llms/huggingface_text_gen_inference.py +0 -23
- langchain/llms/human.py +0 -23
- langchain/llms/javelin_ai_gateway.py +0 -28
- langchain/llms/koboldai.py +0 -23
- langchain/llms/llamacpp.py +0 -23
- langchain/llms/loading.py +0 -27
- langchain/llms/manifest.py +0 -23
- langchain/llms/minimax.py +0 -23
- langchain/llms/mlflow.py +0 -23
- langchain/llms/mlflow_ai_gateway.py +0 -23
- langchain/llms/modal.py +0 -23
- langchain/llms/mosaicml.py +0 -23
- langchain/llms/nlpcloud.py +0 -23
- langchain/llms/octoai_endpoint.py +0 -23
- langchain/llms/ollama.py +0 -23
- langchain/llms/opaqueprompts.py +0 -23
- langchain/llms/openai.py +0 -32
- langchain/llms/openllm.py +0 -23
- langchain/llms/openlm.py +0 -23
- langchain/llms/pai_eas_endpoint.py +0 -23
- langchain/llms/petals.py +0 -23
- langchain/llms/pipelineai.py +0 -23
- langchain/llms/predibase.py +0 -23
- langchain/llms/predictionguard.py +0 -23
- langchain/llms/promptlayer_openai.py +0 -27
- langchain/llms/replicate.py +0 -23
- langchain/llms/rwkv.py +0 -23
- langchain/llms/sagemaker_endpoint.py +0 -28
- langchain/llms/self_hosted.py +0 -23
- langchain/llms/self_hosted_hugging_face.py +0 -23
- langchain/llms/stochasticai.py +0 -23
- langchain/llms/symblai_nebula.py +0 -23
- langchain/llms/textgen.py +0 -23
- langchain/llms/titan_takeoff.py +0 -23
- langchain/llms/titan_takeoff_pro.py +0 -23
- langchain/llms/together.py +0 -23
- langchain/llms/tongyi.py +0 -23
- langchain/llms/utils.py +0 -23
- langchain/llms/vertexai.py +0 -27
- langchain/llms/vllm.py +0 -27
- langchain/llms/volcengine_maas.py +0 -28
- langchain/llms/watsonxllm.py +0 -23
- langchain/llms/writer.py +0 -23
- langchain/llms/xinference.py +0 -23
- langchain/llms/yandex.py +0 -23
- langchain/load/__init__.py +0 -11
- langchain/load/dump.py +0 -3
- langchain/load/load.py +0 -3
- langchain/load/serializable.py +0 -19
- langchain/memory/__init__.py +0 -153
- langchain/memory/buffer.py +0 -178
- langchain/memory/buffer_window.py +0 -62
- langchain/memory/chat_memory.py +0 -104
- langchain/memory/chat_message_histories/__init__.py +0 -84
- langchain/memory/chat_message_histories/astradb.py +0 -25
- langchain/memory/chat_message_histories/cassandra.py +0 -25
- langchain/memory/chat_message_histories/cosmos_db.py +0 -25
- langchain/memory/chat_message_histories/dynamodb.py +0 -25
- langchain/memory/chat_message_histories/elasticsearch.py +0 -27
- langchain/memory/chat_message_histories/file.py +0 -25
- langchain/memory/chat_message_histories/firestore.py +0 -25
- langchain/memory/chat_message_histories/in_memory.py +0 -5
- langchain/memory/chat_message_histories/momento.py +0 -25
- langchain/memory/chat_message_histories/mongodb.py +0 -25
- langchain/memory/chat_message_histories/neo4j.py +0 -25
- langchain/memory/chat_message_histories/postgres.py +0 -25
- langchain/memory/chat_message_histories/redis.py +0 -25
- langchain/memory/chat_message_histories/rocksetdb.py +0 -25
- langchain/memory/chat_message_histories/singlestoredb.py +0 -27
- langchain/memory/chat_message_histories/sql.py +0 -33
- langchain/memory/chat_message_histories/streamlit.py +0 -25
- langchain/memory/chat_message_histories/upstash_redis.py +0 -27
- langchain/memory/chat_message_histories/xata.py +0 -25
- langchain/memory/chat_message_histories/zep.py +0 -25
- langchain/memory/combined.py +0 -85
- langchain/memory/entity.py +0 -611
- langchain/memory/kg.py +0 -23
- langchain/memory/motorhead_memory.py +0 -23
- langchain/memory/prompt.py +0 -164
- langchain/memory/readonly.py +0 -24
- langchain/memory/simple.py +0 -27
- langchain/memory/summary.py +0 -170
- langchain/memory/summary_buffer.py +0 -151
- langchain/memory/token_buffer.py +0 -74
- langchain/memory/utils.py +0 -21
- langchain/memory/vectorstore.py +0 -120
- langchain/memory/vectorstore_token_buffer_memory.py +0 -184
- langchain/memory/zep_memory.py +0 -23
- langchain/model_laboratory.py +0 -99
- langchain/output_parsers/__init__.py +0 -87
- langchain/output_parsers/boolean.py +0 -54
- langchain/output_parsers/combining.py +0 -59
- langchain/output_parsers/datetime.py +0 -58
- langchain/output_parsers/enum.py +0 -45
- langchain/output_parsers/ernie_functions.py +0 -45
- langchain/output_parsers/fix.py +0 -155
- langchain/output_parsers/format_instructions.py +0 -79
- langchain/output_parsers/json.py +0 -15
- langchain/output_parsers/list.py +0 -13
- langchain/output_parsers/loading.py +0 -22
- langchain/output_parsers/openai_functions.py +0 -13
- langchain/output_parsers/openai_tools.py +0 -7
- langchain/output_parsers/pandas_dataframe.py +0 -171
- langchain/output_parsers/prompts.py +0 -21
- langchain/output_parsers/pydantic.py +0 -3
- langchain/output_parsers/rail_parser.py +0 -25
- langchain/output_parsers/regex.py +0 -41
- langchain/output_parsers/regex_dict.py +0 -43
- langchain/output_parsers/retry.py +0 -316
- langchain/output_parsers/structured.py +0 -116
- langchain/output_parsers/xml.py +0 -3
- langchain/output_parsers/yaml.py +0 -77
- langchain/prompts/__init__.py +0 -102
- langchain/prompts/base.py +0 -21
- langchain/prompts/chat.py +0 -37
- langchain/prompts/example_selector/__init__.py +0 -42
- langchain/prompts/example_selector/base.py +0 -3
- langchain/prompts/example_selector/length_based.py +0 -5
- langchain/prompts/example_selector/ngram_overlap.py +0 -32
- langchain/prompts/example_selector/semantic_similarity.py +0 -11
- langchain/prompts/few_shot.py +0 -11
- langchain/prompts/few_shot_with_templates.py +0 -3
- langchain/prompts/loading.py +0 -23
- langchain/prompts/pipeline.py +0 -3
- langchain/prompts/prompt.py +0 -6
- langchain/pydantic_v1/__init__.py +0 -38
- langchain/pydantic_v1/dataclasses.py +0 -20
- langchain/pydantic_v1/main.py +0 -20
- langchain/python.py +0 -19
- langchain/requests.py +0 -35
- langchain/retrievers/__init__.py +0 -178
- langchain/retrievers/arcee.py +0 -23
- langchain/retrievers/arxiv.py +0 -23
- langchain/retrievers/azure_ai_search.py +0 -30
- langchain/retrievers/bedrock.py +0 -33
- langchain/retrievers/bm25.py +0 -28
- langchain/retrievers/chaindesk.py +0 -23
- langchain/retrievers/chatgpt_plugin_retriever.py +0 -23
- langchain/retrievers/cohere_rag_retriever.py +0 -23
- langchain/retrievers/contextual_compression.py +0 -81
- langchain/retrievers/databerry.py +0 -23
- langchain/retrievers/docarray.py +0 -28
- langchain/retrievers/document_compressors/__init__.py +0 -44
- langchain/retrievers/document_compressors/base.py +0 -82
- langchain/retrievers/document_compressors/chain_extract.py +0 -123
- langchain/retrievers/document_compressors/chain_extract_prompt.py +0 -10
- langchain/retrievers/document_compressors/chain_filter.py +0 -133
- langchain/retrievers/document_compressors/chain_filter_prompt.py +0 -8
- langchain/retrievers/document_compressors/cohere_rerank.py +0 -126
- langchain/retrievers/document_compressors/cross_encoder.py +0 -16
- langchain/retrievers/document_compressors/cross_encoder_rerank.py +0 -50
- langchain/retrievers/document_compressors/embeddings_filter.py +0 -140
- langchain/retrievers/document_compressors/flashrank_rerank.py +0 -27
- langchain/retrievers/document_compressors/listwise_rerank.py +0 -145
- langchain/retrievers/elastic_search_bm25.py +0 -23
- langchain/retrievers/embedchain.py +0 -23
- langchain/retrievers/ensemble.py +0 -336
- langchain/retrievers/google_cloud_documentai_warehouse.py +0 -25
- langchain/retrievers/google_vertex_ai_search.py +0 -33
- langchain/retrievers/kay.py +0 -23
- langchain/retrievers/kendra.py +0 -66
- langchain/retrievers/knn.py +0 -23
- langchain/retrievers/llama_index.py +0 -30
- langchain/retrievers/merger_retriever.py +0 -123
- langchain/retrievers/metal.py +0 -23
- langchain/retrievers/milvus.py +0 -28
- langchain/retrievers/multi_query.py +0 -233
- langchain/retrievers/multi_vector.py +0 -135
- langchain/retrievers/outline.py +0 -23
- langchain/retrievers/parent_document_retriever.py +0 -172
- langchain/retrievers/pinecone_hybrid_search.py +0 -23
- langchain/retrievers/pubmed.py +0 -23
- langchain/retrievers/pupmed.py +0 -23
- langchain/retrievers/re_phraser.py +0 -89
- langchain/retrievers/remote_retriever.py +0 -23
- langchain/retrievers/self_query/__init__.py +0 -0
- langchain/retrievers/self_query/astradb.py +0 -23
- langchain/retrievers/self_query/base.py +0 -416
- langchain/retrievers/self_query/chroma.py +0 -23
- langchain/retrievers/self_query/dashvector.py +0 -23
- langchain/retrievers/self_query/databricks_vector_search.py +0 -27
- langchain/retrievers/self_query/deeplake.py +0 -27
- langchain/retrievers/self_query/dingo.py +0 -23
- langchain/retrievers/self_query/elasticsearch.py +0 -25
- langchain/retrievers/self_query/milvus.py +0 -27
- langchain/retrievers/self_query/mongodb_atlas.py +0 -25
- langchain/retrievers/self_query/myscale.py +0 -23
- langchain/retrievers/self_query/opensearch.py +0 -23
- langchain/retrievers/self_query/pgvector.py +0 -23
- langchain/retrievers/self_query/pinecone.py +0 -23
- langchain/retrievers/self_query/qdrant.py +0 -23
- langchain/retrievers/self_query/redis.py +0 -23
- langchain/retrievers/self_query/supabase.py +0 -23
- langchain/retrievers/self_query/tencentvectordb.py +0 -27
- langchain/retrievers/self_query/timescalevector.py +0 -27
- langchain/retrievers/self_query/vectara.py +0 -27
- langchain/retrievers/self_query/weaviate.py +0 -23
- langchain/retrievers/svm.py +0 -23
- langchain/retrievers/tavily_search_api.py +0 -28
- langchain/retrievers/tfidf.py +0 -23
- langchain/retrievers/time_weighted_retriever.py +0 -196
- langchain/retrievers/vespa_retriever.py +0 -23
- langchain/retrievers/weaviate_hybrid_search.py +0 -23
- langchain/retrievers/web_research.py +0 -29
- langchain/retrievers/wikipedia.py +0 -23
- langchain/retrievers/you.py +0 -23
- langchain/retrievers/zep.py +0 -30
- langchain/retrievers/zilliz.py +0 -28
- langchain/runnables/__init__.py +0 -18
- langchain/runnables/hub.py +0 -44
- langchain/runnables/openai_functions.py +0 -57
- langchain/schema/__init__.py +0 -82
- langchain/schema/agent.py +0 -3
- langchain/schema/cache.py +0 -3
- langchain/schema/callbacks/__init__.py +0 -0
- langchain/schema/callbacks/base.py +0 -23
- langchain/schema/callbacks/manager.py +0 -55
- langchain/schema/callbacks/stdout.py +0 -3
- langchain/schema/callbacks/streaming_stdout.py +0 -3
- langchain/schema/callbacks/tracers/__init__.py +0 -0
- langchain/schema/callbacks/tracers/base.py +0 -4
- langchain/schema/callbacks/tracers/evaluation.py +0 -6
- langchain/schema/callbacks/tracers/langchain.py +0 -8
- langchain/schema/callbacks/tracers/langchain_v1.py +0 -3
- langchain/schema/callbacks/tracers/log_stream.py +0 -9
- langchain/schema/callbacks/tracers/root_listeners.py +0 -3
- langchain/schema/callbacks/tracers/run_collector.py +0 -3
- langchain/schema/callbacks/tracers/schemas.py +0 -27
- langchain/schema/callbacks/tracers/stdout.py +0 -13
- langchain/schema/chat.py +0 -3
- langchain/schema/chat_history.py +0 -3
- langchain/schema/document.py +0 -3
- langchain/schema/embeddings.py +0 -3
- langchain/schema/exceptions.py +0 -3
- langchain/schema/language_model.py +0 -15
- langchain/schema/memory.py +0 -3
- langchain/schema/messages.py +0 -51
- langchain/schema/output.py +0 -19
- langchain/schema/output_parser.py +0 -25
- langchain/schema/prompt.py +0 -3
- langchain/schema/prompt_template.py +0 -3
- langchain/schema/retriever.py +0 -3
- langchain/schema/runnable/__init__.py +0 -58
- langchain/schema/runnable/base.py +0 -38
- langchain/schema/runnable/branch.py +0 -3
- langchain/schema/runnable/config.py +0 -27
- langchain/schema/runnable/configurable.py +0 -15
- langchain/schema/runnable/fallbacks.py +0 -3
- langchain/schema/runnable/history.py +0 -11
- langchain/schema/runnable/passthrough.py +0 -8
- langchain/schema/runnable/retry.py +0 -3
- langchain/schema/runnable/router.py +0 -3
- langchain/schema/runnable/utils.py +0 -51
- langchain/schema/storage.py +0 -3
- langchain/schema/vectorstore.py +0 -3
- langchain/serpapi.py +0 -25
- langchain/smith/__init__.py +0 -103
- langchain/smith/evaluation/__init__.py +0 -68
- langchain/smith/evaluation/config.py +0 -365
- langchain/smith/evaluation/name_generation.py +0 -727
- langchain/smith/evaluation/progress.py +0 -146
- langchain/smith/evaluation/runner_utils.py +0 -1689
- langchain/smith/evaluation/string_run_evaluator.py +0 -467
- langchain/sql_database.py +0 -25
- langchain/storage/__init__.py +0 -57
- langchain/storage/_lc_store.py +0 -91
- langchain/storage/encoder_backed.py +0 -128
- langchain/storage/exceptions.py +0 -3
- langchain/storage/file_system.py +0 -176
- langchain/storage/in_memory.py +0 -13
- langchain/storage/redis.py +0 -23
- langchain/storage/upstash_redis.py +0 -27
- langchain/text_splitter.py +0 -50
- langchain/tools/ainetwork/__init__.py +0 -0
- langchain/tools/ainetwork/app.py +0 -30
- langchain/tools/ainetwork/base.py +0 -27
- langchain/tools/ainetwork/owner.py +0 -28
- langchain/tools/ainetwork/rule.py +0 -28
- langchain/tools/ainetwork/transfer.py +0 -28
- langchain/tools/ainetwork/value.py +0 -28
- langchain/tools/amadeus/__init__.py +0 -30
- langchain/tools/amadeus/base.py +0 -23
- langchain/tools/amadeus/closest_airport.py +0 -30
- langchain/tools/amadeus/flight_search.py +0 -30
- langchain/tools/arxiv/__init__.py +0 -1
- langchain/tools/arxiv/tool.py +0 -28
- langchain/tools/azure_cognitive_services/__init__.py +0 -41
- langchain/tools/azure_cognitive_services/form_recognizer.py +0 -23
- langchain/tools/azure_cognitive_services/image_analysis.py +0 -23
- langchain/tools/azure_cognitive_services/speech2text.py +0 -23
- langchain/tools/azure_cognitive_services/text2speech.py +0 -23
- langchain/tools/azure_cognitive_services/text_analytics_health.py +0 -23
- langchain/tools/base.py +0 -19
- langchain/tools/bearly/__init__.py +0 -0
- langchain/tools/bearly/tool.py +0 -33
- langchain/tools/bing_search/__init__.py +0 -29
- langchain/tools/bing_search/tool.py +0 -27
- langchain/tools/brave_search/__init__.py +0 -0
- langchain/tools/brave_search/tool.py +0 -23
- langchain/tools/clickup/__init__.py +0 -0
- langchain/tools/clickup/tool.py +0 -23
- langchain/tools/convert_to_openai.py +0 -4
- langchain/tools/dataforseo_api_search/__init__.py +0 -34
- langchain/tools/dataforseo_api_search/tool.py +0 -32
- langchain/tools/ddg_search/__init__.py +0 -25
- langchain/tools/ddg_search/tool.py +0 -32
- langchain/tools/e2b_data_analysis/__init__.py +0 -0
- langchain/tools/e2b_data_analysis/tool.py +0 -33
- langchain/tools/edenai/__init__.py +0 -50
- langchain/tools/edenai/audio_speech_to_text.py +0 -23
- langchain/tools/edenai/audio_text_to_speech.py +0 -23
- langchain/tools/edenai/edenai_base_tool.py +0 -23
- langchain/tools/edenai/image_explicitcontent.py +0 -23
- langchain/tools/edenai/image_objectdetection.py +0 -23
- langchain/tools/edenai/ocr_identityparser.py +0 -23
- langchain/tools/edenai/ocr_invoiceparser.py +0 -23
- langchain/tools/edenai/text_moderation.py +0 -23
- langchain/tools/eleven_labs/__init__.py +0 -25
- langchain/tools/eleven_labs/models.py +0 -23
- langchain/tools/eleven_labs/text2speech.py +0 -23
- langchain/tools/file_management/__init__.py +0 -47
- langchain/tools/file_management/copy.py +0 -28
- langchain/tools/file_management/delete.py +0 -28
- langchain/tools/file_management/file_search.py +0 -28
- langchain/tools/file_management/list_dir.py +0 -28
- langchain/tools/file_management/move.py +0 -28
- langchain/tools/file_management/read.py +0 -28
- langchain/tools/file_management/write.py +0 -28
- langchain/tools/github/__init__.py +0 -1
- langchain/tools/github/tool.py +0 -23
- langchain/tools/gitlab/__init__.py +0 -1
- langchain/tools/gitlab/tool.py +0 -23
- langchain/tools/gmail/__init__.py +0 -41
- langchain/tools/gmail/base.py +0 -23
- langchain/tools/gmail/create_draft.py +0 -28
- langchain/tools/gmail/get_message.py +0 -28
- langchain/tools/gmail/get_thread.py +0 -28
- langchain/tools/gmail/search.py +0 -30
- langchain/tools/gmail/send_message.py +0 -28
- langchain/tools/golden_query/__init__.py +0 -25
- langchain/tools/golden_query/tool.py +0 -23
- langchain/tools/google_cloud/__init__.py +0 -25
- langchain/tools/google_cloud/texttospeech.py +0 -23
- langchain/tools/google_finance/__init__.py +0 -27
- langchain/tools/google_finance/tool.py +0 -25
- langchain/tools/google_jobs/__init__.py +0 -25
- langchain/tools/google_jobs/tool.py +0 -23
- langchain/tools/google_lens/__init__.py +0 -25
- langchain/tools/google_lens/tool.py +0 -23
- langchain/tools/google_places/__init__.py +0 -25
- langchain/tools/google_places/tool.py +0 -28
- langchain/tools/google_scholar/__init__.py +0 -27
- langchain/tools/google_scholar/tool.py +0 -25
- langchain/tools/google_search/__init__.py +0 -29
- langchain/tools/google_search/tool.py +0 -27
- langchain/tools/google_serper/__init__.py +0 -30
- langchain/tools/google_serper/tool.py +0 -27
- langchain/tools/google_trends/__init__.py +0 -27
- langchain/tools/google_trends/tool.py +0 -25
- langchain/tools/graphql/__init__.py +0 -1
- langchain/tools/graphql/tool.py +0 -23
- langchain/tools/human/__init__.py +0 -25
- langchain/tools/human/tool.py +0 -23
- langchain/tools/ifttt.py +0 -23
- langchain/tools/interaction/__init__.py +0 -1
- langchain/tools/interaction/tool.py +0 -23
- langchain/tools/jira/__init__.py +0 -1
- langchain/tools/jira/tool.py +0 -42
- langchain/tools/json/__init__.py +0 -1
- langchain/tools/json/tool.py +0 -52
- langchain/tools/memorize/__init__.py +0 -25
- langchain/tools/memorize/tool.py +0 -27
- langchain/tools/merriam_webster/__init__.py +0 -1
- langchain/tools/merriam_webster/tool.py +0 -23
- langchain/tools/metaphor_search/__init__.py +0 -25
- langchain/tools/metaphor_search/tool.py +0 -23
- langchain/tools/multion/__init__.py +0 -33
- langchain/tools/multion/close_session.py +0 -30
- langchain/tools/multion/create_session.py +0 -30
- langchain/tools/multion/update_session.py +0 -30
- langchain/tools/nasa/__init__.py +0 -0
- langchain/tools/nasa/tool.py +0 -23
- langchain/tools/nuclia/__init__.py +0 -23
- langchain/tools/nuclia/tool.py +0 -27
- langchain/tools/office365/__init__.py +0 -41
- langchain/tools/office365/base.py +0 -23
- langchain/tools/office365/create_draft_message.py +0 -32
- langchain/tools/office365/events_search.py +0 -28
- langchain/tools/office365/messages_search.py +0 -28
- langchain/tools/office365/send_event.py +0 -28
- langchain/tools/office365/send_message.py +0 -28
- langchain/tools/openapi/__init__.py +0 -0
- langchain/tools/openapi/utils/__init__.py +0 -0
- langchain/tools/openapi/utils/api_models.py +0 -54
- langchain/tools/openapi/utils/openapi_utils.py +0 -30
- langchain/tools/openweathermap/__init__.py +0 -25
- langchain/tools/openweathermap/tool.py +0 -23
- langchain/tools/playwright/__init__.py +0 -47
- langchain/tools/playwright/base.py +0 -23
- langchain/tools/playwright/click.py +0 -28
- langchain/tools/playwright/current_page.py +0 -23
- langchain/tools/playwright/extract_hyperlinks.py +0 -32
- langchain/tools/playwright/extract_text.py +0 -23
- langchain/tools/playwright/get_elements.py +0 -28
- langchain/tools/playwright/navigate.py +0 -28
- langchain/tools/playwright/navigate_back.py +0 -23
- langchain/tools/plugin.py +0 -32
- langchain/tools/powerbi/__init__.py +0 -1
- langchain/tools/powerbi/tool.py +0 -33
- langchain/tools/pubmed/__init__.py +0 -1
- langchain/tools/pubmed/tool.py +0 -23
- langchain/tools/python/__init__.py +0 -13
- langchain/tools/reddit_search/__init__.py +0 -0
- langchain/tools/reddit_search/tool.py +0 -27
- langchain/tools/render.py +0 -23
- langchain/tools/requests/__init__.py +0 -1
- langchain/tools/requests/tool.py +0 -42
- langchain/tools/retriever.py +0 -11
- langchain/tools/scenexplain/__init__.py +0 -1
- langchain/tools/scenexplain/tool.py +0 -28
- langchain/tools/searchapi/__init__.py +0 -30
- langchain/tools/searchapi/tool.py +0 -27
- langchain/tools/searx_search/__init__.py +0 -0
- langchain/tools/searx_search/tool.py +0 -27
- langchain/tools/shell/__init__.py +0 -25
- langchain/tools/shell/tool.py +0 -28
- langchain/tools/slack/__init__.py +0 -38
- langchain/tools/slack/base.py +0 -23
- langchain/tools/slack/get_channel.py +0 -23
- langchain/tools/slack/get_message.py +0 -28
- langchain/tools/slack/schedule_message.py +0 -28
- langchain/tools/slack/send_message.py +0 -28
- langchain/tools/sleep/__init__.py +0 -1
- langchain/tools/sleep/tool.py +0 -28
- langchain/tools/spark_sql/__init__.py +0 -1
- langchain/tools/spark_sql/tool.py +0 -39
- langchain/tools/sql_database/__init__.py +0 -1
- langchain/tools/sql_database/prompt.py +0 -24
- langchain/tools/sql_database/tool.py +0 -39
- langchain/tools/stackexchange/__init__.py +0 -1
- langchain/tools/stackexchange/tool.py +0 -23
- langchain/tools/steam/__init__.py +0 -1
- langchain/tools/steam/tool.py +0 -23
- langchain/tools/steamship_image_generation/__init__.py +0 -25
- langchain/tools/steamship_image_generation/tool.py +0 -28
- langchain/tools/tavily_search/__init__.py +0 -32
- langchain/tools/tavily_search/tool.py +0 -33
- langchain/tools/vectorstore/__init__.py +0 -1
- langchain/tools/vectorstore/tool.py +0 -30
- langchain/tools/wikipedia/__init__.py +0 -1
- langchain/tools/wikipedia/tool.py +0 -23
- langchain/tools/wolfram_alpha/__init__.py +0 -25
- langchain/tools/wolfram_alpha/tool.py +0 -23
- langchain/tools/yahoo_finance_news.py +0 -23
- langchain/tools/youtube/__init__.py +0 -0
- langchain/tools/youtube/search.py +0 -23
- langchain/tools/zapier/__init__.py +0 -29
- langchain/tools/zapier/tool.py +0 -49
- langchain/utilities/__init__.py +0 -168
- langchain/utilities/alpha_vantage.py +0 -23
- langchain/utilities/anthropic.py +0 -30
- langchain/utilities/apify.py +0 -23
- langchain/utilities/arcee.py +0 -45
- langchain/utilities/arxiv.py +0 -23
- langchain/utilities/asyncio.py +0 -11
- langchain/utilities/awslambda.py +0 -23
- langchain/utilities/bibtex.py +0 -23
- langchain/utilities/bing_search.py +0 -23
- langchain/utilities/brave_search.py +0 -23
- langchain/utilities/clickup.py +0 -45
- langchain/utilities/dalle_image_generator.py +0 -25
- langchain/utilities/dataforseo_api_search.py +0 -25
- langchain/utilities/duckduckgo_search.py +0 -23
- langchain/utilities/github.py +0 -23
- langchain/utilities/gitlab.py +0 -23
- langchain/utilities/golden_query.py +0 -23
- langchain/utilities/google_finance.py +0 -23
- langchain/utilities/google_jobs.py +0 -23
- langchain/utilities/google_lens.py +0 -23
- langchain/utilities/google_places_api.py +0 -23
- langchain/utilities/google_scholar.py +0 -23
- langchain/utilities/google_search.py +0 -23
- langchain/utilities/google_serper.py +0 -23
- langchain/utilities/google_trends.py +0 -23
- langchain/utilities/graphql.py +0 -23
- langchain/utilities/jira.py +0 -23
- langchain/utilities/loading.py +0 -4
- langchain/utilities/max_compute.py +0 -23
- langchain/utilities/merriam_webster.py +0 -23
- langchain/utilities/metaphor_search.py +0 -23
- langchain/utilities/nasa.py +0 -23
- langchain/utilities/opaqueprompts.py +0 -27
- langchain/utilities/openapi.py +0 -28
- langchain/utilities/openweathermap.py +0 -23
- langchain/utilities/outline.py +0 -23
- langchain/utilities/portkey.py +0 -23
- langchain/utilities/powerbi.py +0 -23
- langchain/utilities/pubmed.py +0 -23
- langchain/utilities/python.py +0 -19
- langchain/utilities/reddit_search.py +0 -25
- langchain/utilities/redis.py +0 -33
- langchain/utilities/requests.py +0 -27
- langchain/utilities/scenexplain.py +0 -23
- langchain/utilities/searchapi.py +0 -23
- langchain/utilities/searx_search.py +0 -28
- langchain/utilities/serpapi.py +0 -28
- langchain/utilities/spark_sql.py +0 -23
- langchain/utilities/sql_database.py +0 -28
- langchain/utilities/stackexchange.py +0 -23
- langchain/utilities/steam.py +0 -23
- langchain/utilities/tavily_search.py +0 -25
- langchain/utilities/tensorflow_datasets.py +0 -23
- langchain/utilities/twilio.py +0 -23
- langchain/utilities/vertexai.py +0 -36
- langchain/utilities/wikipedia.py +0 -23
- langchain/utilities/wolfram_alpha.py +0 -23
- langchain/utilities/zapier.py +0 -23
- langchain/utils/__init__.py +0 -77
- langchain/utils/aiter.py +0 -3
- langchain/utils/env.py +0 -3
- langchain/utils/ernie_functions.py +0 -36
- langchain/utils/formatting.py +0 -3
- langchain/utils/html.py +0 -19
- langchain/utils/input.py +0 -8
- langchain/utils/iter.py +0 -3
- langchain/utils/json_schema.py +0 -11
- langchain/utils/loading.py +0 -3
- langchain/utils/math.py +0 -32
- langchain/utils/openai.py +0 -23
- langchain/utils/openai_functions.py +0 -13
- langchain/utils/pydantic.py +0 -3
- langchain/utils/strings.py +0 -3
- langchain/utils/utils.py +0 -21
- langchain/vectorstores/__init__.py +0 -262
- langchain/vectorstores/alibabacloud_opensearch.py +0 -30
- langchain/vectorstores/analyticdb.py +0 -23
- langchain/vectorstores/annoy.py +0 -23
- langchain/vectorstores/astradb.py +0 -23
- langchain/vectorstores/atlas.py +0 -23
- langchain/vectorstores/awadb.py +0 -23
- langchain/vectorstores/azure_cosmos_db.py +0 -28
- langchain/vectorstores/azuresearch.py +0 -30
- langchain/vectorstores/bageldb.py +0 -23
- langchain/vectorstores/baiducloud_vector_search.py +0 -23
- langchain/vectorstores/base.py +0 -3
- langchain/vectorstores/cassandra.py +0 -23
- langchain/vectorstores/chroma.py +0 -23
- langchain/vectorstores/clarifai.py +0 -23
- langchain/vectorstores/clickhouse.py +0 -27
- langchain/vectorstores/dashvector.py +0 -23
- langchain/vectorstores/databricks_vector_search.py +0 -23
- langchain/vectorstores/deeplake.py +0 -23
- langchain/vectorstores/dingo.py +0 -23
- langchain/vectorstores/docarray/__init__.py +0 -30
- langchain/vectorstores/docarray/base.py +0 -23
- langchain/vectorstores/docarray/hnsw.py +0 -23
- langchain/vectorstores/docarray/in_memory.py +0 -23
- langchain/vectorstores/elastic_vector_search.py +0 -27
- langchain/vectorstores/elasticsearch.py +0 -39
- langchain/vectorstores/epsilla.py +0 -23
- langchain/vectorstores/faiss.py +0 -23
- langchain/vectorstores/hippo.py +0 -23
- langchain/vectorstores/hologres.py +0 -23
- langchain/vectorstores/lancedb.py +0 -23
- langchain/vectorstores/llm_rails.py +0 -28
- langchain/vectorstores/marqo.py +0 -23
- langchain/vectorstores/matching_engine.py +0 -23
- langchain/vectorstores/meilisearch.py +0 -23
- langchain/vectorstores/milvus.py +0 -23
- langchain/vectorstores/momento_vector_index.py +0 -23
- langchain/vectorstores/mongodb_atlas.py +0 -23
- langchain/vectorstores/myscale.py +0 -30
- langchain/vectorstores/neo4j_vector.py +0 -28
- langchain/vectorstores/nucliadb.py +0 -23
- langchain/vectorstores/opensearch_vector_search.py +0 -23
- langchain/vectorstores/pgembedding.py +0 -36
- langchain/vectorstores/pgvecto_rs.py +0 -23
- langchain/vectorstores/pgvector.py +0 -28
- langchain/vectorstores/pinecone.py +0 -23
- langchain/vectorstores/qdrant.py +0 -28
- langchain/vectorstores/redis/__init__.py +0 -42
- langchain/vectorstores/redis/base.py +0 -33
- langchain/vectorstores/redis/filters.py +0 -48
- langchain/vectorstores/redis/schema.py +0 -54
- langchain/vectorstores/rocksetdb.py +0 -23
- langchain/vectorstores/scann.py +0 -23
- langchain/vectorstores/semadb.py +0 -23
- langchain/vectorstores/singlestoredb.py +0 -23
- langchain/vectorstores/sklearn.py +0 -42
- langchain/vectorstores/sqlitevss.py +0 -23
- langchain/vectorstores/starrocks.py +0 -28
- langchain/vectorstores/supabase.py +0 -23
- langchain/vectorstores/tair.py +0 -23
- langchain/vectorstores/tencentvectordb.py +0 -33
- langchain/vectorstores/tigris.py +0 -23
- langchain/vectorstores/tiledb.py +0 -23
- langchain/vectorstores/timescalevector.py +0 -23
- langchain/vectorstores/typesense.py +0 -23
- langchain/vectorstores/usearch.py +0 -23
- langchain/vectorstores/utils.py +0 -33
- langchain/vectorstores/vald.py +0 -23
- langchain/vectorstores/vearch.py +0 -23
- langchain/vectorstores/vectara.py +0 -28
- langchain/vectorstores/vespa.py +0 -23
- langchain/vectorstores/weaviate.py +0 -23
- langchain/vectorstores/xata.py +0 -23
- langchain/vectorstores/yellowbrick.py +0 -23
- langchain/vectorstores/zep.py +0 -28
- langchain/vectorstores/zilliz.py +0 -23
- langchain-0.4.0.dev0.dist-info/METADATA +0 -134
- langchain-0.4.0.dev0.dist-info/RECORD +0 -1341
- langchain-0.4.0.dev0.dist-info/entry_points.txt +0 -4
- {langchain-0.4.0.dev0.dist-info → langchain-1.0.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,1572 @@
|
|
|
1
|
+
"""Types for middleware and agents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
6
|
+
from dataclasses import dataclass, field, replace
|
|
7
|
+
from inspect import iscoroutinefunction
|
|
8
|
+
from typing import (
|
|
9
|
+
TYPE_CHECKING,
|
|
10
|
+
Annotated,
|
|
11
|
+
Any,
|
|
12
|
+
Generic,
|
|
13
|
+
Literal,
|
|
14
|
+
Protocol,
|
|
15
|
+
cast,
|
|
16
|
+
overload,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from collections.abc import Awaitable
|
|
21
|
+
|
|
22
|
+
from langchain.tools.tool_node import ToolCallRequest
|
|
23
|
+
|
|
24
|
+
# Needed as top level import for Pydantic schema generation on AgentState
|
|
25
|
+
from typing import TypeAlias
|
|
26
|
+
|
|
27
|
+
from langchain_core.messages import AIMessage, AnyMessage, BaseMessage, ToolMessage # noqa: TC002
|
|
28
|
+
from langgraph.channels.ephemeral_value import EphemeralValue
|
|
29
|
+
from langgraph.graph.message import add_messages
|
|
30
|
+
from langgraph.types import Command # noqa: TC002
|
|
31
|
+
from langgraph.typing import ContextT
|
|
32
|
+
from typing_extensions import NotRequired, Required, TypedDict, TypeVar, Unpack
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
from langchain_core.language_models.chat_models import BaseChatModel
|
|
36
|
+
from langchain_core.tools import BaseTool
|
|
37
|
+
from langgraph.runtime import Runtime
|
|
38
|
+
|
|
39
|
+
from langchain.agents.structured_output import ResponseFormat
|
|
40
|
+
|
|
41
|
+
__all__ = [
|
|
42
|
+
"AgentMiddleware",
|
|
43
|
+
"AgentState",
|
|
44
|
+
"ContextT",
|
|
45
|
+
"ModelRequest",
|
|
46
|
+
"ModelResponse",
|
|
47
|
+
"OmitFromSchema",
|
|
48
|
+
"after_agent",
|
|
49
|
+
"after_model",
|
|
50
|
+
"before_agent",
|
|
51
|
+
"before_model",
|
|
52
|
+
"dynamic_prompt",
|
|
53
|
+
"hook_config",
|
|
54
|
+
"wrap_tool_call",
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
JumpTo = Literal["tools", "model", "end"]
|
|
58
|
+
"""Destination to jump to when a middleware node returns."""
|
|
59
|
+
|
|
60
|
+
ResponseT = TypeVar("ResponseT")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class _ModelRequestOverrides(TypedDict, total=False):
|
|
64
|
+
"""Possible overrides for ModelRequest.override() method."""
|
|
65
|
+
|
|
66
|
+
model: BaseChatModel
|
|
67
|
+
system_prompt: str | None
|
|
68
|
+
messages: list[AnyMessage]
|
|
69
|
+
tool_choice: Any | None
|
|
70
|
+
tools: list[BaseTool | dict]
|
|
71
|
+
response_format: ResponseFormat | None
|
|
72
|
+
model_settings: dict[str, Any]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class ModelRequest:
|
|
77
|
+
"""Model request information for the agent."""
|
|
78
|
+
|
|
79
|
+
model: BaseChatModel
|
|
80
|
+
system_prompt: str | None
|
|
81
|
+
messages: list[AnyMessage] # excluding system prompt
|
|
82
|
+
tool_choice: Any | None
|
|
83
|
+
tools: list[BaseTool | dict]
|
|
84
|
+
response_format: ResponseFormat | None
|
|
85
|
+
state: AgentState
|
|
86
|
+
runtime: Runtime[ContextT] # type: ignore[valid-type]
|
|
87
|
+
model_settings: dict[str, Any] = field(default_factory=dict)
|
|
88
|
+
|
|
89
|
+
def override(self, **overrides: Unpack[_ModelRequestOverrides]) -> ModelRequest:
|
|
90
|
+
"""Replace the request with a new request with the given overrides.
|
|
91
|
+
|
|
92
|
+
Returns a new `ModelRequest` instance with the specified attributes replaced.
|
|
93
|
+
This follows an immutable pattern, leaving the original request unchanged.
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
**overrides: Keyword arguments for attributes to override. Supported keys:
|
|
97
|
+
- model: BaseChatModel instance
|
|
98
|
+
- system_prompt: Optional system prompt string
|
|
99
|
+
- messages: List of messages
|
|
100
|
+
- tool_choice: Tool choice configuration
|
|
101
|
+
- tools: List of available tools
|
|
102
|
+
- response_format: Response format specification
|
|
103
|
+
- model_settings: Additional model settings
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
New ModelRequest instance with specified overrides applied.
|
|
107
|
+
|
|
108
|
+
Examples:
|
|
109
|
+
```python
|
|
110
|
+
# Create a new request with different model
|
|
111
|
+
new_request = request.override(model=different_model)
|
|
112
|
+
|
|
113
|
+
# Override multiple attributes
|
|
114
|
+
new_request = request.override(system_prompt="New instructions", tool_choice="auto")
|
|
115
|
+
```
|
|
116
|
+
"""
|
|
117
|
+
return replace(self, **overrides)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@dataclass
|
|
121
|
+
class ModelResponse:
|
|
122
|
+
"""Response from model execution including messages and optional structured output.
|
|
123
|
+
|
|
124
|
+
The result will usually contain a single AIMessage, but may include
|
|
125
|
+
an additional ToolMessage if the model used a tool for structured output.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
result: list[BaseMessage]
|
|
129
|
+
"""List of messages from model execution."""
|
|
130
|
+
|
|
131
|
+
structured_response: Any = None
|
|
132
|
+
"""Parsed structured output if response_format was specified, None otherwise."""
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# Type alias for middleware return type - allows returning either full response or just AIMessage
|
|
136
|
+
ModelCallResult: TypeAlias = "ModelResponse | AIMessage"
|
|
137
|
+
"""Type alias for model call handler return value.
|
|
138
|
+
|
|
139
|
+
Middleware can return either:
|
|
140
|
+
- ModelResponse: Full response with messages and optional structured output
|
|
141
|
+
- AIMessage: Simplified return for simple use cases
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@dataclass
|
|
146
|
+
class OmitFromSchema:
|
|
147
|
+
"""Annotation used to mark state attributes as omitted from input or output schemas."""
|
|
148
|
+
|
|
149
|
+
input: bool = True
|
|
150
|
+
"""Whether to omit the attribute from the input schema."""
|
|
151
|
+
|
|
152
|
+
output: bool = True
|
|
153
|
+
"""Whether to omit the attribute from the output schema."""
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
OmitFromInput = OmitFromSchema(input=True, output=False)
|
|
157
|
+
"""Annotation used to mark state attributes as omitted from input schema."""
|
|
158
|
+
|
|
159
|
+
OmitFromOutput = OmitFromSchema(input=False, output=True)
|
|
160
|
+
"""Annotation used to mark state attributes as omitted from output schema."""
|
|
161
|
+
|
|
162
|
+
PrivateStateAttr = OmitFromSchema(input=True, output=True)
|
|
163
|
+
"""Annotation used to mark state attributes as purely internal for a given middleware."""
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class AgentState(TypedDict, Generic[ResponseT]):
|
|
167
|
+
"""State schema for the agent."""
|
|
168
|
+
|
|
169
|
+
messages: Required[Annotated[list[AnyMessage], add_messages]]
|
|
170
|
+
jump_to: NotRequired[Annotated[JumpTo | None, EphemeralValue, PrivateStateAttr]]
|
|
171
|
+
structured_response: NotRequired[Annotated[ResponseT, OmitFromInput]]
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class _InputAgentState(TypedDict): # noqa: PYI049
|
|
175
|
+
"""Input state schema for the agent."""
|
|
176
|
+
|
|
177
|
+
messages: Required[Annotated[list[AnyMessage | dict], add_messages]]
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class _OutputAgentState(TypedDict, Generic[ResponseT]): # noqa: PYI049
|
|
181
|
+
"""Output state schema for the agent."""
|
|
182
|
+
|
|
183
|
+
messages: Required[Annotated[list[AnyMessage], add_messages]]
|
|
184
|
+
structured_response: NotRequired[ResponseT]
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
StateT = TypeVar("StateT", bound=AgentState, default=AgentState)
|
|
188
|
+
StateT_contra = TypeVar("StateT_contra", bound=AgentState, contravariant=True)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class AgentMiddleware(Generic[StateT, ContextT]):
|
|
192
|
+
"""Base middleware class for an agent.
|
|
193
|
+
|
|
194
|
+
Subclass this and implement any of the defined methods to customize agent behavior
|
|
195
|
+
between steps in the main agent loop.
|
|
196
|
+
"""
|
|
197
|
+
|
|
198
|
+
state_schema: type[StateT] = cast("type[StateT]", AgentState)
|
|
199
|
+
"""The schema for state passed to the middleware nodes."""
|
|
200
|
+
|
|
201
|
+
tools: list[BaseTool]
|
|
202
|
+
"""Additional tools registered by the middleware."""
|
|
203
|
+
|
|
204
|
+
@property
|
|
205
|
+
def name(self) -> str:
|
|
206
|
+
"""The name of the middleware instance.
|
|
207
|
+
|
|
208
|
+
Defaults to the class name, but can be overridden for custom naming.
|
|
209
|
+
"""
|
|
210
|
+
return self.__class__.__name__
|
|
211
|
+
|
|
212
|
+
def before_agent(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:
|
|
213
|
+
"""Logic to run before the agent execution starts."""
|
|
214
|
+
|
|
215
|
+
async def abefore_agent(
|
|
216
|
+
self, state: StateT, runtime: Runtime[ContextT]
|
|
217
|
+
) -> dict[str, Any] | None:
|
|
218
|
+
"""Async logic to run before the agent execution starts."""
|
|
219
|
+
|
|
220
|
+
def before_model(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:
|
|
221
|
+
"""Logic to run before the model is called."""
|
|
222
|
+
|
|
223
|
+
async def abefore_model(
|
|
224
|
+
self, state: StateT, runtime: Runtime[ContextT]
|
|
225
|
+
) -> dict[str, Any] | None:
|
|
226
|
+
"""Async logic to run before the model is called."""
|
|
227
|
+
|
|
228
|
+
def after_model(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:
|
|
229
|
+
"""Logic to run after the model is called."""
|
|
230
|
+
|
|
231
|
+
async def aafter_model(
|
|
232
|
+
self, state: StateT, runtime: Runtime[ContextT]
|
|
233
|
+
) -> dict[str, Any] | None:
|
|
234
|
+
"""Async logic to run after the model is called."""
|
|
235
|
+
|
|
236
|
+
def wrap_model_call(
|
|
237
|
+
self,
|
|
238
|
+
request: ModelRequest,
|
|
239
|
+
handler: Callable[[ModelRequest], ModelResponse],
|
|
240
|
+
) -> ModelCallResult:
|
|
241
|
+
"""Intercept and control model execution via handler callback.
|
|
242
|
+
|
|
243
|
+
The handler callback executes the model request and returns a `ModelResponse`.
|
|
244
|
+
Middleware can call the handler multiple times for retry logic, skip calling
|
|
245
|
+
it to short-circuit, or modify the request/response. Multiple middleware
|
|
246
|
+
compose with first in list as outermost layer.
|
|
247
|
+
|
|
248
|
+
Args:
|
|
249
|
+
request: Model request to execute (includes state and runtime).
|
|
250
|
+
handler: Callback that executes the model request and returns
|
|
251
|
+
`ModelResponse`. Call this to execute the model. Can be called multiple
|
|
252
|
+
times for retry logic. Can skip calling it to short-circuit.
|
|
253
|
+
|
|
254
|
+
Returns:
|
|
255
|
+
`ModelCallResult`
|
|
256
|
+
|
|
257
|
+
Examples:
|
|
258
|
+
Retry on error:
|
|
259
|
+
```python
|
|
260
|
+
def wrap_model_call(self, request, handler):
|
|
261
|
+
for attempt in range(3):
|
|
262
|
+
try:
|
|
263
|
+
return handler(request)
|
|
264
|
+
except Exception:
|
|
265
|
+
if attempt == 2:
|
|
266
|
+
raise
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Rewrite response:
|
|
270
|
+
```python
|
|
271
|
+
def wrap_model_call(self, request, handler):
|
|
272
|
+
response = handler(request)
|
|
273
|
+
ai_msg = response.result[0]
|
|
274
|
+
return ModelResponse(
|
|
275
|
+
result=[AIMessage(content=f"[{ai_msg.content}]")],
|
|
276
|
+
structured_response=response.structured_response,
|
|
277
|
+
)
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
Error to fallback:
|
|
281
|
+
```python
|
|
282
|
+
def wrap_model_call(self, request, handler):
|
|
283
|
+
try:
|
|
284
|
+
return handler(request)
|
|
285
|
+
except Exception:
|
|
286
|
+
return ModelResponse(result=[AIMessage(content="Service unavailable")])
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
Cache/short-circuit:
|
|
290
|
+
```python
|
|
291
|
+
def wrap_model_call(self, request, handler):
|
|
292
|
+
if cached := get_cache(request):
|
|
293
|
+
return cached # Short-circuit with cached result
|
|
294
|
+
response = handler(request)
|
|
295
|
+
save_cache(request, response)
|
|
296
|
+
return response
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
Simple AIMessage return (converted automatically):
|
|
300
|
+
```python
|
|
301
|
+
def wrap_model_call(self, request, handler):
|
|
302
|
+
response = handler(request)
|
|
303
|
+
# Can return AIMessage directly for simple cases
|
|
304
|
+
return AIMessage(content="Simplified response")
|
|
305
|
+
```
|
|
306
|
+
"""
|
|
307
|
+
msg = (
|
|
308
|
+
"Synchronous implementation of wrap_model_call is not available. "
|
|
309
|
+
"You are likely encountering this error because you defined only the async version "
|
|
310
|
+
"(awrap_model_call) and invoked your agent in a synchronous context "
|
|
311
|
+
"(e.g., using `stream()` or `invoke()`). "
|
|
312
|
+
"To resolve this, either: "
|
|
313
|
+
"(1) subclass AgentMiddleware and implement the synchronous wrap_model_call method, "
|
|
314
|
+
"(2) use the @wrap_model_call decorator on a standalone sync function, or "
|
|
315
|
+
"(3) invoke your agent asynchronously using `astream()` or `ainvoke()`."
|
|
316
|
+
)
|
|
317
|
+
raise NotImplementedError(msg)
|
|
318
|
+
|
|
319
|
+
async def awrap_model_call(
|
|
320
|
+
self,
|
|
321
|
+
request: ModelRequest,
|
|
322
|
+
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
|
|
323
|
+
) -> ModelCallResult:
|
|
324
|
+
"""Intercept and control async model execution via handler callback.
|
|
325
|
+
|
|
326
|
+
The handler callback executes the model request and returns a `ModelResponse`.
|
|
327
|
+
Middleware can call the handler multiple times for retry logic, skip calling
|
|
328
|
+
it to short-circuit, or modify the request/response. Multiple middleware
|
|
329
|
+
compose with first in list as outermost layer.
|
|
330
|
+
|
|
331
|
+
Args:
|
|
332
|
+
request: Model request to execute (includes state and runtime).
|
|
333
|
+
handler: Async callback that executes the model request and returns
|
|
334
|
+
`ModelResponse`. Call this to execute the model. Can be called multiple
|
|
335
|
+
times for retry logic. Can skip calling it to short-circuit.
|
|
336
|
+
|
|
337
|
+
Returns:
|
|
338
|
+
ModelCallResult
|
|
339
|
+
|
|
340
|
+
Examples:
|
|
341
|
+
Retry on error:
|
|
342
|
+
```python
|
|
343
|
+
async def awrap_model_call(self, request, handler):
|
|
344
|
+
for attempt in range(3):
|
|
345
|
+
try:
|
|
346
|
+
return await handler(request)
|
|
347
|
+
except Exception:
|
|
348
|
+
if attempt == 2:
|
|
349
|
+
raise
|
|
350
|
+
```
|
|
351
|
+
"""
|
|
352
|
+
msg = (
|
|
353
|
+
"Asynchronous implementation of awrap_model_call is not available. "
|
|
354
|
+
"You are likely encountering this error because you defined only the sync version "
|
|
355
|
+
"(wrap_model_call) and invoked your agent in an asynchronous context "
|
|
356
|
+
"(e.g., using `astream()` or `ainvoke()`). "
|
|
357
|
+
"To resolve this, either: "
|
|
358
|
+
"(1) subclass AgentMiddleware and implement the asynchronous awrap_model_call method, "
|
|
359
|
+
"(2) use the @wrap_model_call decorator on a standalone async function, or "
|
|
360
|
+
"(3) invoke your agent synchronously using `stream()` or `invoke()`."
|
|
361
|
+
)
|
|
362
|
+
raise NotImplementedError(msg)
|
|
363
|
+
|
|
364
|
+
def after_agent(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:
|
|
365
|
+
"""Logic to run after the agent execution completes."""
|
|
366
|
+
|
|
367
|
+
async def aafter_agent(
|
|
368
|
+
self, state: StateT, runtime: Runtime[ContextT]
|
|
369
|
+
) -> dict[str, Any] | None:
|
|
370
|
+
"""Async logic to run after the agent execution completes."""
|
|
371
|
+
|
|
372
|
+
def wrap_tool_call(
|
|
373
|
+
self,
|
|
374
|
+
request: ToolCallRequest,
|
|
375
|
+
handler: Callable[[ToolCallRequest], ToolMessage | Command],
|
|
376
|
+
) -> ToolMessage | Command:
|
|
377
|
+
"""Intercept tool execution for retries, monitoring, or modification.
|
|
378
|
+
|
|
379
|
+
Multiple middleware compose automatically (first defined = outermost).
|
|
380
|
+
Exceptions propagate unless `handle_tool_errors` is configured on `ToolNode`.
|
|
381
|
+
|
|
382
|
+
Args:
|
|
383
|
+
request: Tool call request with call `dict`, `BaseTool`, state, and runtime.
|
|
384
|
+
Access state via `request.state` and runtime via `request.runtime`.
|
|
385
|
+
handler: Callable to execute the tool (can be called multiple times).
|
|
386
|
+
|
|
387
|
+
Returns:
|
|
388
|
+
`ToolMessage` or `Command` (the final result).
|
|
389
|
+
|
|
390
|
+
The handler callable can be invoked multiple times for retry logic.
|
|
391
|
+
Each call to handler is independent and stateless.
|
|
392
|
+
|
|
393
|
+
Examples:
|
|
394
|
+
Modify request before execution:
|
|
395
|
+
|
|
396
|
+
```python
|
|
397
|
+
def wrap_tool_call(self, request, handler):
|
|
398
|
+
request.tool_call["args"]["value"] *= 2
|
|
399
|
+
return handler(request)
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
Retry on error (call handler multiple times):
|
|
403
|
+
|
|
404
|
+
```python
|
|
405
|
+
def wrap_tool_call(self, request, handler):
|
|
406
|
+
for attempt in range(3):
|
|
407
|
+
try:
|
|
408
|
+
result = handler(request)
|
|
409
|
+
if is_valid(result):
|
|
410
|
+
return result
|
|
411
|
+
except Exception:
|
|
412
|
+
if attempt == 2:
|
|
413
|
+
raise
|
|
414
|
+
return result
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
Conditional retry based on response:
|
|
418
|
+
|
|
419
|
+
```python
|
|
420
|
+
def wrap_tool_call(self, request, handler):
|
|
421
|
+
for attempt in range(3):
|
|
422
|
+
result = handler(request)
|
|
423
|
+
if isinstance(result, ToolMessage) and result.status != "error":
|
|
424
|
+
return result
|
|
425
|
+
if attempt < 2:
|
|
426
|
+
continue
|
|
427
|
+
return result
|
|
428
|
+
```
|
|
429
|
+
"""
|
|
430
|
+
msg = (
|
|
431
|
+
"Synchronous implementation of wrap_tool_call is not available. "
|
|
432
|
+
"You are likely encountering this error because you defined only the async version "
|
|
433
|
+
"(awrap_tool_call) and invoked your agent in a synchronous context "
|
|
434
|
+
"(e.g., using `stream()` or `invoke()`). "
|
|
435
|
+
"To resolve this, either: "
|
|
436
|
+
"(1) subclass AgentMiddleware and implement the synchronous wrap_tool_call method, "
|
|
437
|
+
"(2) use the @wrap_tool_call decorator on a standalone sync function, or "
|
|
438
|
+
"(3) invoke your agent asynchronously using `astream()` or `ainvoke()`."
|
|
439
|
+
)
|
|
440
|
+
raise NotImplementedError(msg)
|
|
441
|
+
|
|
442
|
+
async def awrap_tool_call(
|
|
443
|
+
self,
|
|
444
|
+
request: ToolCallRequest,
|
|
445
|
+
handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]],
|
|
446
|
+
) -> ToolMessage | Command:
|
|
447
|
+
"""Intercept and control async tool execution via handler callback.
|
|
448
|
+
|
|
449
|
+
The handler callback executes the tool call and returns a `ToolMessage` or
|
|
450
|
+
`Command`. Middleware can call the handler multiple times for retry logic, skip
|
|
451
|
+
calling it to short-circuit, or modify the request/response. Multiple middleware
|
|
452
|
+
compose with first in list as outermost layer.
|
|
453
|
+
|
|
454
|
+
Args:
|
|
455
|
+
request: Tool call request with call `dict`, `BaseTool`, state, and runtime.
|
|
456
|
+
Access state via `request.state` and runtime via `request.runtime`.
|
|
457
|
+
handler: Async callable to execute the tool and returns `ToolMessage` or
|
|
458
|
+
`Command`. Call this to execute the tool. Can be called multiple times
|
|
459
|
+
for retry logic. Can skip calling it to short-circuit.
|
|
460
|
+
|
|
461
|
+
Returns:
|
|
462
|
+
`ToolMessage` or `Command` (the final result).
|
|
463
|
+
|
|
464
|
+
The handler callable can be invoked multiple times for retry logic.
|
|
465
|
+
Each call to handler is independent and stateless.
|
|
466
|
+
|
|
467
|
+
Examples:
|
|
468
|
+
Async retry on error:
|
|
469
|
+
```python
|
|
470
|
+
async def awrap_tool_call(self, request, handler):
|
|
471
|
+
for attempt in range(3):
|
|
472
|
+
try:
|
|
473
|
+
result = await handler(request)
|
|
474
|
+
if is_valid(result):
|
|
475
|
+
return result
|
|
476
|
+
except Exception:
|
|
477
|
+
if attempt == 2:
|
|
478
|
+
raise
|
|
479
|
+
return result
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
```python
|
|
483
|
+
async def awrap_tool_call(self, request, handler):
|
|
484
|
+
if cached := await get_cache_async(request):
|
|
485
|
+
return ToolMessage(content=cached, tool_call_id=request.tool_call["id"])
|
|
486
|
+
result = await handler(request)
|
|
487
|
+
await save_cache_async(request, result)
|
|
488
|
+
return result
|
|
489
|
+
```
|
|
490
|
+
"""
|
|
491
|
+
msg = (
|
|
492
|
+
"Asynchronous implementation of awrap_tool_call is not available. "
|
|
493
|
+
"You are likely encountering this error because you defined only the sync version "
|
|
494
|
+
"(wrap_tool_call) and invoked your agent in an asynchronous context "
|
|
495
|
+
"(e.g., using `astream()` or `ainvoke()`). "
|
|
496
|
+
"To resolve this, either: "
|
|
497
|
+
"(1) subclass AgentMiddleware and implement the asynchronous awrap_tool_call method, "
|
|
498
|
+
"(2) use the @wrap_tool_call decorator on a standalone async function, or "
|
|
499
|
+
"(3) invoke your agent synchronously using `stream()` or `invoke()`."
|
|
500
|
+
)
|
|
501
|
+
raise NotImplementedError(msg)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
class _CallableWithStateAndRuntime(Protocol[StateT_contra, ContextT]):
|
|
505
|
+
"""Callable with `AgentState` and `Runtime` as arguments."""
|
|
506
|
+
|
|
507
|
+
def __call__(
|
|
508
|
+
self, state: StateT_contra, runtime: Runtime[ContextT]
|
|
509
|
+
) -> dict[str, Any] | Command | None | Awaitable[dict[str, Any] | Command | None]:
|
|
510
|
+
"""Perform some logic with the state and runtime."""
|
|
511
|
+
...
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
class _CallableReturningPromptString(Protocol[StateT_contra, ContextT]): # type: ignore[misc]
|
|
515
|
+
"""Callable that returns a prompt string given `ModelRequest` (contains state and runtime)."""
|
|
516
|
+
|
|
517
|
+
def __call__(self, request: ModelRequest) -> str | Awaitable[str]:
|
|
518
|
+
"""Generate a system prompt string based on the request."""
|
|
519
|
+
...
|
|
520
|
+
|
|
521
|
+
|
|
522
|
+
class _CallableReturningModelResponse(Protocol[StateT_contra, ContextT]): # type: ignore[misc]
|
|
523
|
+
"""Callable for model call interception with handler callback.
|
|
524
|
+
|
|
525
|
+
Receives handler callback to execute model and returns `ModelResponse` or
|
|
526
|
+
`AIMessage`.
|
|
527
|
+
"""
|
|
528
|
+
|
|
529
|
+
def __call__(
|
|
530
|
+
self,
|
|
531
|
+
request: ModelRequest,
|
|
532
|
+
handler: Callable[[ModelRequest], ModelResponse],
|
|
533
|
+
) -> ModelCallResult:
|
|
534
|
+
"""Intercept model execution via handler callback."""
|
|
535
|
+
...
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
class _CallableReturningToolResponse(Protocol):
|
|
539
|
+
"""Callable for tool call interception with handler callback.
|
|
540
|
+
|
|
541
|
+
Receives handler callback to execute tool and returns final `ToolMessage` or
|
|
542
|
+
`Command`.
|
|
543
|
+
"""
|
|
544
|
+
|
|
545
|
+
def __call__(
|
|
546
|
+
self,
|
|
547
|
+
request: ToolCallRequest,
|
|
548
|
+
handler: Callable[[ToolCallRequest], ToolMessage | Command],
|
|
549
|
+
) -> ToolMessage | Command:
|
|
550
|
+
"""Intercept tool execution via handler callback."""
|
|
551
|
+
...
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
CallableT = TypeVar("CallableT", bound=Callable[..., Any])
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def hook_config(
|
|
558
|
+
*,
|
|
559
|
+
can_jump_to: list[JumpTo] | None = None,
|
|
560
|
+
) -> Callable[[CallableT], CallableT]:
|
|
561
|
+
"""Decorator to configure hook behavior in middleware methods.
|
|
562
|
+
|
|
563
|
+
Use this decorator on `before_model` or `after_model` methods in middleware classes
|
|
564
|
+
to configure their behavior. Currently supports specifying which destinations they
|
|
565
|
+
can jump to, which establishes conditional edges in the agent graph.
|
|
566
|
+
|
|
567
|
+
Args:
|
|
568
|
+
can_jump_to: Optional list of valid jump destinations. Can be:
|
|
569
|
+
- "tools": Jump to the tools node
|
|
570
|
+
- "model": Jump back to the model node
|
|
571
|
+
- "end": Jump to the end of the graph
|
|
572
|
+
|
|
573
|
+
Returns:
|
|
574
|
+
Decorator function that marks the method with configuration metadata.
|
|
575
|
+
|
|
576
|
+
Examples:
|
|
577
|
+
Using decorator on a class method:
|
|
578
|
+
```python
|
|
579
|
+
class MyMiddleware(AgentMiddleware):
|
|
580
|
+
@hook_config(can_jump_to=["end", "model"])
|
|
581
|
+
def before_model(self, state: AgentState) -> dict[str, Any] | None:
|
|
582
|
+
if some_condition(state):
|
|
583
|
+
return {"jump_to": "end"}
|
|
584
|
+
return None
|
|
585
|
+
```
|
|
586
|
+
|
|
587
|
+
Alternative: Use the `can_jump_to` parameter in `before_model`/`after_model` decorators:
|
|
588
|
+
```python
|
|
589
|
+
@before_model(can_jump_to=["end"])
|
|
590
|
+
def conditional_middleware(state: AgentState) -> dict[str, Any] | None:
|
|
591
|
+
if should_exit(state):
|
|
592
|
+
return {"jump_to": "end"}
|
|
593
|
+
return None
|
|
594
|
+
```
|
|
595
|
+
"""
|
|
596
|
+
|
|
597
|
+
def decorator(func: CallableT) -> CallableT:
|
|
598
|
+
if can_jump_to is not None:
|
|
599
|
+
func.__can_jump_to__ = can_jump_to # type: ignore[attr-defined]
|
|
600
|
+
return func
|
|
601
|
+
|
|
602
|
+
return decorator
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
@overload
|
|
606
|
+
def before_model(
|
|
607
|
+
func: _CallableWithStateAndRuntime[StateT, ContextT],
|
|
608
|
+
) -> AgentMiddleware[StateT, ContextT]: ...
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
@overload
|
|
612
|
+
def before_model(
|
|
613
|
+
func: None = None,
|
|
614
|
+
*,
|
|
615
|
+
state_schema: type[StateT] | None = None,
|
|
616
|
+
tools: list[BaseTool] | None = None,
|
|
617
|
+
can_jump_to: list[JumpTo] | None = None,
|
|
618
|
+
name: str | None = None,
|
|
619
|
+
) -> Callable[
|
|
620
|
+
[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]
|
|
621
|
+
]: ...
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def before_model(
|
|
625
|
+
func: _CallableWithStateAndRuntime[StateT, ContextT] | None = None,
|
|
626
|
+
*,
|
|
627
|
+
state_schema: type[StateT] | None = None,
|
|
628
|
+
tools: list[BaseTool] | None = None,
|
|
629
|
+
can_jump_to: list[JumpTo] | None = None,
|
|
630
|
+
name: str | None = None,
|
|
631
|
+
) -> (
|
|
632
|
+
Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]
|
|
633
|
+
| AgentMiddleware[StateT, ContextT]
|
|
634
|
+
):
|
|
635
|
+
"""Decorator used to dynamically create a middleware with the `before_model` hook.
|
|
636
|
+
|
|
637
|
+
Args:
|
|
638
|
+
func: The function to be decorated. Must accept:
|
|
639
|
+
`state: StateT, runtime: Runtime[ContextT]` - State and runtime context
|
|
640
|
+
state_schema: Optional custom state schema type. If not provided, uses the default
|
|
641
|
+
`AgentState` schema.
|
|
642
|
+
tools: Optional list of additional tools to register with this middleware.
|
|
643
|
+
can_jump_to: Optional list of valid jump destinations for conditional edges.
|
|
644
|
+
Valid values are: `"tools"`, `"model"`, `"end"`
|
|
645
|
+
name: Optional name for the generated middleware class. If not provided,
|
|
646
|
+
uses the decorated function's name.
|
|
647
|
+
|
|
648
|
+
Returns:
|
|
649
|
+
Either an `AgentMiddleware` instance (if func is provided directly) or a
|
|
650
|
+
decorator function that can be applied to a function it is wrapping.
|
|
651
|
+
|
|
652
|
+
The decorated function should return:
|
|
653
|
+
- `dict[str, Any]` - State updates to merge into the agent state
|
|
654
|
+
- `Command` - A command to control flow (e.g., jump to different node)
|
|
655
|
+
- `None` - No state updates or flow control
|
|
656
|
+
|
|
657
|
+
Examples:
|
|
658
|
+
Basic usage:
|
|
659
|
+
```python
|
|
660
|
+
@before_model
|
|
661
|
+
def log_before_model(state: AgentState, runtime: Runtime) -> None:
|
|
662
|
+
print(f"About to call model with {len(state['messages'])} messages")
|
|
663
|
+
```
|
|
664
|
+
|
|
665
|
+
With conditional jumping:
|
|
666
|
+
```python
|
|
667
|
+
@before_model(can_jump_to=["end"])
|
|
668
|
+
def conditional_before_model(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
|
|
669
|
+
if some_condition(state):
|
|
670
|
+
return {"jump_to": "end"}
|
|
671
|
+
return None
|
|
672
|
+
```
|
|
673
|
+
|
|
674
|
+
With custom state schema:
|
|
675
|
+
```python
|
|
676
|
+
@before_model(state_schema=MyCustomState)
|
|
677
|
+
def custom_before_model(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:
|
|
678
|
+
return {"custom_field": "updated_value"}
|
|
679
|
+
```
|
|
680
|
+
"""
|
|
681
|
+
|
|
682
|
+
def decorator(
|
|
683
|
+
func: _CallableWithStateAndRuntime[StateT, ContextT],
|
|
684
|
+
) -> AgentMiddleware[StateT, ContextT]:
|
|
685
|
+
is_async = iscoroutinefunction(func)
|
|
686
|
+
|
|
687
|
+
func_can_jump_to = (
|
|
688
|
+
can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])
|
|
689
|
+
)
|
|
690
|
+
|
|
691
|
+
if is_async:
|
|
692
|
+
|
|
693
|
+
async def async_wrapped(
|
|
694
|
+
self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
|
|
695
|
+
state: StateT,
|
|
696
|
+
runtime: Runtime[ContextT],
|
|
697
|
+
) -> dict[str, Any] | Command | None:
|
|
698
|
+
return await func(state, runtime) # type: ignore[misc]
|
|
699
|
+
|
|
700
|
+
# Preserve can_jump_to metadata on the wrapped function
|
|
701
|
+
if func_can_jump_to:
|
|
702
|
+
async_wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]
|
|
703
|
+
|
|
704
|
+
middleware_name = name or cast(
|
|
705
|
+
"str", getattr(func, "__name__", "BeforeModelMiddleware")
|
|
706
|
+
)
|
|
707
|
+
|
|
708
|
+
return type(
|
|
709
|
+
middleware_name,
|
|
710
|
+
(AgentMiddleware,),
|
|
711
|
+
{
|
|
712
|
+
"state_schema": state_schema or AgentState,
|
|
713
|
+
"tools": tools or [],
|
|
714
|
+
"abefore_model": async_wrapped,
|
|
715
|
+
},
|
|
716
|
+
)()
|
|
717
|
+
|
|
718
|
+
def wrapped(
|
|
719
|
+
self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
|
|
720
|
+
state: StateT,
|
|
721
|
+
runtime: Runtime[ContextT],
|
|
722
|
+
) -> dict[str, Any] | Command | None:
|
|
723
|
+
return func(state, runtime) # type: ignore[return-value]
|
|
724
|
+
|
|
725
|
+
# Preserve can_jump_to metadata on the wrapped function
|
|
726
|
+
if func_can_jump_to:
|
|
727
|
+
wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]
|
|
728
|
+
|
|
729
|
+
# Use function name as default if no name provided
|
|
730
|
+
middleware_name = name or cast("str", getattr(func, "__name__", "BeforeModelMiddleware"))
|
|
731
|
+
|
|
732
|
+
return type(
|
|
733
|
+
middleware_name,
|
|
734
|
+
(AgentMiddleware,),
|
|
735
|
+
{
|
|
736
|
+
"state_schema": state_schema or AgentState,
|
|
737
|
+
"tools": tools or [],
|
|
738
|
+
"before_model": wrapped,
|
|
739
|
+
},
|
|
740
|
+
)()
|
|
741
|
+
|
|
742
|
+
if func is not None:
|
|
743
|
+
return decorator(func)
|
|
744
|
+
return decorator
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
@overload
|
|
748
|
+
def after_model(
|
|
749
|
+
func: _CallableWithStateAndRuntime[StateT, ContextT],
|
|
750
|
+
) -> AgentMiddleware[StateT, ContextT]: ...
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
@overload
|
|
754
|
+
def after_model(
|
|
755
|
+
func: None = None,
|
|
756
|
+
*,
|
|
757
|
+
state_schema: type[StateT] | None = None,
|
|
758
|
+
tools: list[BaseTool] | None = None,
|
|
759
|
+
can_jump_to: list[JumpTo] | None = None,
|
|
760
|
+
name: str | None = None,
|
|
761
|
+
) -> Callable[
|
|
762
|
+
[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]
|
|
763
|
+
]: ...
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
def after_model(
|
|
767
|
+
func: _CallableWithStateAndRuntime[StateT, ContextT] | None = None,
|
|
768
|
+
*,
|
|
769
|
+
state_schema: type[StateT] | None = None,
|
|
770
|
+
tools: list[BaseTool] | None = None,
|
|
771
|
+
can_jump_to: list[JumpTo] | None = None,
|
|
772
|
+
name: str | None = None,
|
|
773
|
+
) -> (
|
|
774
|
+
Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]
|
|
775
|
+
| AgentMiddleware[StateT, ContextT]
|
|
776
|
+
):
|
|
777
|
+
"""Decorator used to dynamically create a middleware with the `after_model` hook.
|
|
778
|
+
|
|
779
|
+
Args:
|
|
780
|
+
func: The function to be decorated. Must accept:
|
|
781
|
+
`state: StateT, runtime: Runtime[ContextT]` - State and runtime context
|
|
782
|
+
state_schema: Optional custom state schema type. If not provided, uses the
|
|
783
|
+
default `AgentState` schema.
|
|
784
|
+
tools: Optional list of additional tools to register with this middleware.
|
|
785
|
+
can_jump_to: Optional list of valid jump destinations for conditional edges.
|
|
786
|
+
Valid values are: `"tools"`, `"model"`, `"end"`
|
|
787
|
+
name: Optional name for the generated middleware class. If not provided,
|
|
788
|
+
uses the decorated function's name.
|
|
789
|
+
|
|
790
|
+
Returns:
|
|
791
|
+
Either an `AgentMiddleware` instance (if func is provided) or a decorator
|
|
792
|
+
function that can be applied to a function.
|
|
793
|
+
|
|
794
|
+
The decorated function should return:
|
|
795
|
+
- `dict[str, Any]` - State updates to merge into the agent state
|
|
796
|
+
- `Command` - A command to control flow (e.g., jump to different node)
|
|
797
|
+
- `None` - No state updates or flow control
|
|
798
|
+
|
|
799
|
+
Examples:
|
|
800
|
+
Basic usage for logging model responses:
|
|
801
|
+
```python
|
|
802
|
+
@after_model
|
|
803
|
+
def log_latest_message(state: AgentState, runtime: Runtime) -> None:
|
|
804
|
+
print(state["messages"][-1].content)
|
|
805
|
+
```
|
|
806
|
+
|
|
807
|
+
With custom state schema:
|
|
808
|
+
```python
|
|
809
|
+
@after_model(state_schema=MyCustomState, name="MyAfterModelMiddleware")
|
|
810
|
+
def custom_after_model(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:
|
|
811
|
+
return {"custom_field": "updated_after_model"}
|
|
812
|
+
```
|
|
813
|
+
"""
|
|
814
|
+
|
|
815
|
+
def decorator(
|
|
816
|
+
func: _CallableWithStateAndRuntime[StateT, ContextT],
|
|
817
|
+
) -> AgentMiddleware[StateT, ContextT]:
|
|
818
|
+
is_async = iscoroutinefunction(func)
|
|
819
|
+
# Extract can_jump_to from decorator parameter or from function metadata
|
|
820
|
+
func_can_jump_to = (
|
|
821
|
+
can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])
|
|
822
|
+
)
|
|
823
|
+
|
|
824
|
+
if is_async:
|
|
825
|
+
|
|
826
|
+
async def async_wrapped(
|
|
827
|
+
self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
|
|
828
|
+
state: StateT,
|
|
829
|
+
runtime: Runtime[ContextT],
|
|
830
|
+
) -> dict[str, Any] | Command | None:
|
|
831
|
+
return await func(state, runtime) # type: ignore[misc]
|
|
832
|
+
|
|
833
|
+
# Preserve can_jump_to metadata on the wrapped function
|
|
834
|
+
if func_can_jump_to:
|
|
835
|
+
async_wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]
|
|
836
|
+
|
|
837
|
+
middleware_name = name or cast("str", getattr(func, "__name__", "AfterModelMiddleware"))
|
|
838
|
+
|
|
839
|
+
return type(
|
|
840
|
+
middleware_name,
|
|
841
|
+
(AgentMiddleware,),
|
|
842
|
+
{
|
|
843
|
+
"state_schema": state_schema or AgentState,
|
|
844
|
+
"tools": tools or [],
|
|
845
|
+
"aafter_model": async_wrapped,
|
|
846
|
+
},
|
|
847
|
+
)()
|
|
848
|
+
|
|
849
|
+
def wrapped(
|
|
850
|
+
self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
|
|
851
|
+
state: StateT,
|
|
852
|
+
runtime: Runtime[ContextT],
|
|
853
|
+
) -> dict[str, Any] | Command | None:
|
|
854
|
+
return func(state, runtime) # type: ignore[return-value]
|
|
855
|
+
|
|
856
|
+
# Preserve can_jump_to metadata on the wrapped function
|
|
857
|
+
if func_can_jump_to:
|
|
858
|
+
wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]
|
|
859
|
+
|
|
860
|
+
# Use function name as default if no name provided
|
|
861
|
+
middleware_name = name or cast("str", getattr(func, "__name__", "AfterModelMiddleware"))
|
|
862
|
+
|
|
863
|
+
return type(
|
|
864
|
+
middleware_name,
|
|
865
|
+
(AgentMiddleware,),
|
|
866
|
+
{
|
|
867
|
+
"state_schema": state_schema or AgentState,
|
|
868
|
+
"tools": tools or [],
|
|
869
|
+
"after_model": wrapped,
|
|
870
|
+
},
|
|
871
|
+
)()
|
|
872
|
+
|
|
873
|
+
if func is not None:
|
|
874
|
+
return decorator(func)
|
|
875
|
+
return decorator
|
|
876
|
+
|
|
877
|
+
|
|
878
|
+
@overload
|
|
879
|
+
def before_agent(
|
|
880
|
+
func: _CallableWithStateAndRuntime[StateT, ContextT],
|
|
881
|
+
) -> AgentMiddleware[StateT, ContextT]: ...
|
|
882
|
+
|
|
883
|
+
|
|
884
|
+
@overload
|
|
885
|
+
def before_agent(
|
|
886
|
+
func: None = None,
|
|
887
|
+
*,
|
|
888
|
+
state_schema: type[StateT] | None = None,
|
|
889
|
+
tools: list[BaseTool] | None = None,
|
|
890
|
+
can_jump_to: list[JumpTo] | None = None,
|
|
891
|
+
name: str | None = None,
|
|
892
|
+
) -> Callable[
|
|
893
|
+
[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]
|
|
894
|
+
]: ...
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
def before_agent(
|
|
898
|
+
func: _CallableWithStateAndRuntime[StateT, ContextT] | None = None,
|
|
899
|
+
*,
|
|
900
|
+
state_schema: type[StateT] | None = None,
|
|
901
|
+
tools: list[BaseTool] | None = None,
|
|
902
|
+
can_jump_to: list[JumpTo] | None = None,
|
|
903
|
+
name: str | None = None,
|
|
904
|
+
) -> (
|
|
905
|
+
Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]
|
|
906
|
+
| AgentMiddleware[StateT, ContextT]
|
|
907
|
+
):
|
|
908
|
+
"""Decorator used to dynamically create a middleware with the `before_agent` hook.
|
|
909
|
+
|
|
910
|
+
Args:
|
|
911
|
+
func: The function to be decorated. Must accept:
|
|
912
|
+
`state: StateT, runtime: Runtime[ContextT]` - State and runtime context
|
|
913
|
+
state_schema: Optional custom state schema type. If not provided, uses the
|
|
914
|
+
default `AgentState` schema.
|
|
915
|
+
tools: Optional list of additional tools to register with this middleware.
|
|
916
|
+
can_jump_to: Optional list of valid jump destinations for conditional edges.
|
|
917
|
+
Valid values are: `"tools"`, `"model"`, `"end"`
|
|
918
|
+
name: Optional name for the generated middleware class. If not provided,
|
|
919
|
+
uses the decorated function's name.
|
|
920
|
+
|
|
921
|
+
Returns:
|
|
922
|
+
Either an `AgentMiddleware` instance (if func is provided directly) or a
|
|
923
|
+
decorator function that can be applied to a function it is wrapping.
|
|
924
|
+
|
|
925
|
+
The decorated function should return:
|
|
926
|
+
- `dict[str, Any]` - State updates to merge into the agent state
|
|
927
|
+
- `Command` - A command to control flow (e.g., jump to different node)
|
|
928
|
+
- `None` - No state updates or flow control
|
|
929
|
+
|
|
930
|
+
Examples:
|
|
931
|
+
Basic usage:
|
|
932
|
+
```python
|
|
933
|
+
@before_agent
|
|
934
|
+
def log_before_agent(state: AgentState, runtime: Runtime) -> None:
|
|
935
|
+
print(f"Starting agent with {len(state['messages'])} messages")
|
|
936
|
+
```
|
|
937
|
+
|
|
938
|
+
With conditional jumping:
|
|
939
|
+
```python
|
|
940
|
+
@before_agent(can_jump_to=["end"])
|
|
941
|
+
def conditional_before_agent(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:
|
|
942
|
+
if some_condition(state):
|
|
943
|
+
return {"jump_to": "end"}
|
|
944
|
+
return None
|
|
945
|
+
```
|
|
946
|
+
|
|
947
|
+
With custom state schema:
|
|
948
|
+
```python
|
|
949
|
+
@before_agent(state_schema=MyCustomState)
|
|
950
|
+
def custom_before_agent(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:
|
|
951
|
+
return {"custom_field": "initialized_value"}
|
|
952
|
+
```
|
|
953
|
+
"""
|
|
954
|
+
|
|
955
|
+
def decorator(
|
|
956
|
+
func: _CallableWithStateAndRuntime[StateT, ContextT],
|
|
957
|
+
) -> AgentMiddleware[StateT, ContextT]:
|
|
958
|
+
is_async = iscoroutinefunction(func)
|
|
959
|
+
|
|
960
|
+
func_can_jump_to = (
|
|
961
|
+
can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])
|
|
962
|
+
)
|
|
963
|
+
|
|
964
|
+
if is_async:
|
|
965
|
+
|
|
966
|
+
async def async_wrapped(
|
|
967
|
+
self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
|
|
968
|
+
state: StateT,
|
|
969
|
+
runtime: Runtime[ContextT],
|
|
970
|
+
) -> dict[str, Any] | Command | None:
|
|
971
|
+
return await func(state, runtime) # type: ignore[misc]
|
|
972
|
+
|
|
973
|
+
# Preserve can_jump_to metadata on the wrapped function
|
|
974
|
+
if func_can_jump_to:
|
|
975
|
+
async_wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]
|
|
976
|
+
|
|
977
|
+
middleware_name = name or cast(
|
|
978
|
+
"str", getattr(func, "__name__", "BeforeAgentMiddleware")
|
|
979
|
+
)
|
|
980
|
+
|
|
981
|
+
return type(
|
|
982
|
+
middleware_name,
|
|
983
|
+
(AgentMiddleware,),
|
|
984
|
+
{
|
|
985
|
+
"state_schema": state_schema or AgentState,
|
|
986
|
+
"tools": tools or [],
|
|
987
|
+
"abefore_agent": async_wrapped,
|
|
988
|
+
},
|
|
989
|
+
)()
|
|
990
|
+
|
|
991
|
+
def wrapped(
|
|
992
|
+
self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
|
|
993
|
+
state: StateT,
|
|
994
|
+
runtime: Runtime[ContextT],
|
|
995
|
+
) -> dict[str, Any] | Command | None:
|
|
996
|
+
return func(state, runtime) # type: ignore[return-value]
|
|
997
|
+
|
|
998
|
+
# Preserve can_jump_to metadata on the wrapped function
|
|
999
|
+
if func_can_jump_to:
|
|
1000
|
+
wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]
|
|
1001
|
+
|
|
1002
|
+
# Use function name as default if no name provided
|
|
1003
|
+
middleware_name = name or cast("str", getattr(func, "__name__", "BeforeAgentMiddleware"))
|
|
1004
|
+
|
|
1005
|
+
return type(
|
|
1006
|
+
middleware_name,
|
|
1007
|
+
(AgentMiddleware,),
|
|
1008
|
+
{
|
|
1009
|
+
"state_schema": state_schema or AgentState,
|
|
1010
|
+
"tools": tools or [],
|
|
1011
|
+
"before_agent": wrapped,
|
|
1012
|
+
},
|
|
1013
|
+
)()
|
|
1014
|
+
|
|
1015
|
+
if func is not None:
|
|
1016
|
+
return decorator(func)
|
|
1017
|
+
return decorator
|
|
1018
|
+
|
|
1019
|
+
|
|
1020
|
+
@overload
|
|
1021
|
+
def after_agent(
|
|
1022
|
+
func: _CallableWithStateAndRuntime[StateT, ContextT],
|
|
1023
|
+
) -> AgentMiddleware[StateT, ContextT]: ...
|
|
1024
|
+
|
|
1025
|
+
|
|
1026
|
+
@overload
|
|
1027
|
+
def after_agent(
|
|
1028
|
+
func: None = None,
|
|
1029
|
+
*,
|
|
1030
|
+
state_schema: type[StateT] | None = None,
|
|
1031
|
+
tools: list[BaseTool] | None = None,
|
|
1032
|
+
can_jump_to: list[JumpTo] | None = None,
|
|
1033
|
+
name: str | None = None,
|
|
1034
|
+
) -> Callable[
|
|
1035
|
+
[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]
|
|
1036
|
+
]: ...
|
|
1037
|
+
|
|
1038
|
+
|
|
1039
|
+
def after_agent(
|
|
1040
|
+
func: _CallableWithStateAndRuntime[StateT, ContextT] | None = None,
|
|
1041
|
+
*,
|
|
1042
|
+
state_schema: type[StateT] | None = None,
|
|
1043
|
+
tools: list[BaseTool] | None = None,
|
|
1044
|
+
can_jump_to: list[JumpTo] | None = None,
|
|
1045
|
+
name: str | None = None,
|
|
1046
|
+
) -> (
|
|
1047
|
+
Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]
|
|
1048
|
+
| AgentMiddleware[StateT, ContextT]
|
|
1049
|
+
):
|
|
1050
|
+
"""Decorator used to dynamically create a middleware with the `after_agent` hook.
|
|
1051
|
+
|
|
1052
|
+
Args:
|
|
1053
|
+
func: The function to be decorated. Must accept:
|
|
1054
|
+
`state: StateT, runtime: Runtime[ContextT]` - State and runtime context
|
|
1055
|
+
state_schema: Optional custom state schema type. If not provided, uses the
|
|
1056
|
+
default `AgentState` schema.
|
|
1057
|
+
tools: Optional list of additional tools to register with this middleware.
|
|
1058
|
+
can_jump_to: Optional list of valid jump destinations for conditional edges.
|
|
1059
|
+
Valid values are: `"tools"`, `"model"`, `"end"`
|
|
1060
|
+
name: Optional name for the generated middleware class. If not provided,
|
|
1061
|
+
uses the decorated function's name.
|
|
1062
|
+
|
|
1063
|
+
Returns:
|
|
1064
|
+
Either an `AgentMiddleware` instance (if func is provided) or a decorator
|
|
1065
|
+
function that can be applied to a function.
|
|
1066
|
+
|
|
1067
|
+
The decorated function should return:
|
|
1068
|
+
- `dict[str, Any]` - State updates to merge into the agent state
|
|
1069
|
+
- `Command` - A command to control flow (e.g., jump to different node)
|
|
1070
|
+
- `None` - No state updates or flow control
|
|
1071
|
+
|
|
1072
|
+
Examples:
|
|
1073
|
+
Basic usage for logging agent completion:
|
|
1074
|
+
```python
|
|
1075
|
+
@after_agent
|
|
1076
|
+
def log_completion(state: AgentState, runtime: Runtime) -> None:
|
|
1077
|
+
print(f"Agent completed with {len(state['messages'])} messages")
|
|
1078
|
+
```
|
|
1079
|
+
|
|
1080
|
+
With custom state schema:
|
|
1081
|
+
```python
|
|
1082
|
+
@after_agent(state_schema=MyCustomState, name="MyAfterAgentMiddleware")
|
|
1083
|
+
def custom_after_agent(state: MyCustomState, runtime: Runtime) -> dict[str, Any]:
|
|
1084
|
+
return {"custom_field": "finalized_value"}
|
|
1085
|
+
```
|
|
1086
|
+
"""
|
|
1087
|
+
|
|
1088
|
+
def decorator(
|
|
1089
|
+
func: _CallableWithStateAndRuntime[StateT, ContextT],
|
|
1090
|
+
) -> AgentMiddleware[StateT, ContextT]:
|
|
1091
|
+
is_async = iscoroutinefunction(func)
|
|
1092
|
+
# Extract can_jump_to from decorator parameter or from function metadata
|
|
1093
|
+
func_can_jump_to = (
|
|
1094
|
+
can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])
|
|
1095
|
+
)
|
|
1096
|
+
|
|
1097
|
+
if is_async:
|
|
1098
|
+
|
|
1099
|
+
async def async_wrapped(
|
|
1100
|
+
self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
|
|
1101
|
+
state: StateT,
|
|
1102
|
+
runtime: Runtime[ContextT],
|
|
1103
|
+
) -> dict[str, Any] | Command | None:
|
|
1104
|
+
return await func(state, runtime) # type: ignore[misc]
|
|
1105
|
+
|
|
1106
|
+
# Preserve can_jump_to metadata on the wrapped function
|
|
1107
|
+
if func_can_jump_to:
|
|
1108
|
+
async_wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]
|
|
1109
|
+
|
|
1110
|
+
middleware_name = name or cast("str", getattr(func, "__name__", "AfterAgentMiddleware"))
|
|
1111
|
+
|
|
1112
|
+
return type(
|
|
1113
|
+
middleware_name,
|
|
1114
|
+
(AgentMiddleware,),
|
|
1115
|
+
{
|
|
1116
|
+
"state_schema": state_schema or AgentState,
|
|
1117
|
+
"tools": tools or [],
|
|
1118
|
+
"aafter_agent": async_wrapped,
|
|
1119
|
+
},
|
|
1120
|
+
)()
|
|
1121
|
+
|
|
1122
|
+
def wrapped(
|
|
1123
|
+
self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
|
|
1124
|
+
state: StateT,
|
|
1125
|
+
runtime: Runtime[ContextT],
|
|
1126
|
+
) -> dict[str, Any] | Command | None:
|
|
1127
|
+
return func(state, runtime) # type: ignore[return-value]
|
|
1128
|
+
|
|
1129
|
+
# Preserve can_jump_to metadata on the wrapped function
|
|
1130
|
+
if func_can_jump_to:
|
|
1131
|
+
wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]
|
|
1132
|
+
|
|
1133
|
+
# Use function name as default if no name provided
|
|
1134
|
+
middleware_name = name or cast("str", getattr(func, "__name__", "AfterAgentMiddleware"))
|
|
1135
|
+
|
|
1136
|
+
return type(
|
|
1137
|
+
middleware_name,
|
|
1138
|
+
(AgentMiddleware,),
|
|
1139
|
+
{
|
|
1140
|
+
"state_schema": state_schema or AgentState,
|
|
1141
|
+
"tools": tools or [],
|
|
1142
|
+
"after_agent": wrapped,
|
|
1143
|
+
},
|
|
1144
|
+
)()
|
|
1145
|
+
|
|
1146
|
+
if func is not None:
|
|
1147
|
+
return decorator(func)
|
|
1148
|
+
return decorator
|
|
1149
|
+
|
|
1150
|
+
|
|
1151
|
+
@overload
|
|
1152
|
+
def dynamic_prompt(
|
|
1153
|
+
func: _CallableReturningPromptString[StateT, ContextT],
|
|
1154
|
+
) -> AgentMiddleware[StateT, ContextT]: ...
|
|
1155
|
+
|
|
1156
|
+
|
|
1157
|
+
@overload
|
|
1158
|
+
def dynamic_prompt(
|
|
1159
|
+
func: None = None,
|
|
1160
|
+
) -> Callable[
|
|
1161
|
+
[_CallableReturningPromptString[StateT, ContextT]],
|
|
1162
|
+
AgentMiddleware[StateT, ContextT],
|
|
1163
|
+
]: ...
|
|
1164
|
+
|
|
1165
|
+
|
|
1166
|
+
def dynamic_prompt(
|
|
1167
|
+
func: _CallableReturningPromptString[StateT, ContextT] | None = None,
|
|
1168
|
+
) -> (
|
|
1169
|
+
Callable[
|
|
1170
|
+
[_CallableReturningPromptString[StateT, ContextT]],
|
|
1171
|
+
AgentMiddleware[StateT, ContextT],
|
|
1172
|
+
]
|
|
1173
|
+
| AgentMiddleware[StateT, ContextT]
|
|
1174
|
+
):
|
|
1175
|
+
"""Decorator used to dynamically generate system prompts for the model.
|
|
1176
|
+
|
|
1177
|
+
This is a convenience decorator that creates middleware using `wrap_model_call`
|
|
1178
|
+
specifically for dynamic prompt generation. The decorated function should return
|
|
1179
|
+
a string that will be set as the system prompt for the model request.
|
|
1180
|
+
|
|
1181
|
+
Args:
|
|
1182
|
+
func: The function to be decorated. Must accept:
|
|
1183
|
+
`request: ModelRequest` - Model request (contains state and runtime)
|
|
1184
|
+
|
|
1185
|
+
Returns:
|
|
1186
|
+
Either an AgentMiddleware instance (if func is provided) or a decorator function
|
|
1187
|
+
that can be applied to a function.
|
|
1188
|
+
|
|
1189
|
+
The decorated function should return:
|
|
1190
|
+
- `str` - The system prompt to use for the model request
|
|
1191
|
+
|
|
1192
|
+
Examples:
|
|
1193
|
+
Basic usage with dynamic content:
|
|
1194
|
+
```python
|
|
1195
|
+
@dynamic_prompt
|
|
1196
|
+
def my_prompt(request: ModelRequest) -> str:
|
|
1197
|
+
user_name = request.runtime.context.get("user_name", "User")
|
|
1198
|
+
return f"You are a helpful assistant helping {user_name}."
|
|
1199
|
+
```
|
|
1200
|
+
|
|
1201
|
+
Using state to customize the prompt:
|
|
1202
|
+
```python
|
|
1203
|
+
@dynamic_prompt
|
|
1204
|
+
def context_aware_prompt(request: ModelRequest) -> str:
|
|
1205
|
+
msg_count = len(request.state["messages"])
|
|
1206
|
+
if msg_count > 10:
|
|
1207
|
+
return "You are in a long conversation. Be concise."
|
|
1208
|
+
return "You are a helpful assistant."
|
|
1209
|
+
```
|
|
1210
|
+
|
|
1211
|
+
Using with agent:
|
|
1212
|
+
```python
|
|
1213
|
+
agent = create_agent(model, middleware=[my_prompt])
|
|
1214
|
+
```
|
|
1215
|
+
"""
|
|
1216
|
+
|
|
1217
|
+
def decorator(
|
|
1218
|
+
func: _CallableReturningPromptString[StateT, ContextT],
|
|
1219
|
+
) -> AgentMiddleware[StateT, ContextT]:
|
|
1220
|
+
is_async = iscoroutinefunction(func)
|
|
1221
|
+
|
|
1222
|
+
if is_async:
|
|
1223
|
+
|
|
1224
|
+
async def async_wrapped(
|
|
1225
|
+
self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
|
|
1226
|
+
request: ModelRequest,
|
|
1227
|
+
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
|
|
1228
|
+
) -> ModelCallResult:
|
|
1229
|
+
prompt = await func(request) # type: ignore[misc]
|
|
1230
|
+
request.system_prompt = prompt
|
|
1231
|
+
return await handler(request)
|
|
1232
|
+
|
|
1233
|
+
middleware_name = cast("str", getattr(func, "__name__", "DynamicPromptMiddleware"))
|
|
1234
|
+
|
|
1235
|
+
return type(
|
|
1236
|
+
middleware_name,
|
|
1237
|
+
(AgentMiddleware,),
|
|
1238
|
+
{
|
|
1239
|
+
"state_schema": AgentState,
|
|
1240
|
+
"tools": [],
|
|
1241
|
+
"awrap_model_call": async_wrapped,
|
|
1242
|
+
},
|
|
1243
|
+
)()
|
|
1244
|
+
|
|
1245
|
+
def wrapped(
|
|
1246
|
+
self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
|
|
1247
|
+
request: ModelRequest,
|
|
1248
|
+
handler: Callable[[ModelRequest], ModelResponse],
|
|
1249
|
+
) -> ModelCallResult:
|
|
1250
|
+
prompt = cast("str", func(request))
|
|
1251
|
+
request.system_prompt = prompt
|
|
1252
|
+
return handler(request)
|
|
1253
|
+
|
|
1254
|
+
async def async_wrapped_from_sync(
|
|
1255
|
+
self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
|
|
1256
|
+
request: ModelRequest,
|
|
1257
|
+
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
|
|
1258
|
+
) -> ModelCallResult:
|
|
1259
|
+
# Delegate to sync function
|
|
1260
|
+
prompt = cast("str", func(request))
|
|
1261
|
+
request.system_prompt = prompt
|
|
1262
|
+
return await handler(request)
|
|
1263
|
+
|
|
1264
|
+
middleware_name = cast("str", getattr(func, "__name__", "DynamicPromptMiddleware"))
|
|
1265
|
+
|
|
1266
|
+
return type(
|
|
1267
|
+
middleware_name,
|
|
1268
|
+
(AgentMiddleware,),
|
|
1269
|
+
{
|
|
1270
|
+
"state_schema": AgentState,
|
|
1271
|
+
"tools": [],
|
|
1272
|
+
"wrap_model_call": wrapped,
|
|
1273
|
+
"awrap_model_call": async_wrapped_from_sync,
|
|
1274
|
+
},
|
|
1275
|
+
)()
|
|
1276
|
+
|
|
1277
|
+
if func is not None:
|
|
1278
|
+
return decorator(func)
|
|
1279
|
+
return decorator
|
|
1280
|
+
|
|
1281
|
+
|
|
1282
|
+
@overload
|
|
1283
|
+
def wrap_model_call(
|
|
1284
|
+
func: _CallableReturningModelResponse[StateT, ContextT],
|
|
1285
|
+
) -> AgentMiddleware[StateT, ContextT]: ...
|
|
1286
|
+
|
|
1287
|
+
|
|
1288
|
+
@overload
|
|
1289
|
+
def wrap_model_call(
|
|
1290
|
+
func: None = None,
|
|
1291
|
+
*,
|
|
1292
|
+
state_schema: type[StateT] | None = None,
|
|
1293
|
+
tools: list[BaseTool] | None = None,
|
|
1294
|
+
name: str | None = None,
|
|
1295
|
+
) -> Callable[
|
|
1296
|
+
[_CallableReturningModelResponse[StateT, ContextT]],
|
|
1297
|
+
AgentMiddleware[StateT, ContextT],
|
|
1298
|
+
]: ...
|
|
1299
|
+
|
|
1300
|
+
|
|
1301
|
+
def wrap_model_call(
|
|
1302
|
+
func: _CallableReturningModelResponse[StateT, ContextT] | None = None,
|
|
1303
|
+
*,
|
|
1304
|
+
state_schema: type[StateT] | None = None,
|
|
1305
|
+
tools: list[BaseTool] | None = None,
|
|
1306
|
+
name: str | None = None,
|
|
1307
|
+
) -> (
|
|
1308
|
+
Callable[
|
|
1309
|
+
[_CallableReturningModelResponse[StateT, ContextT]],
|
|
1310
|
+
AgentMiddleware[StateT, ContextT],
|
|
1311
|
+
]
|
|
1312
|
+
| AgentMiddleware[StateT, ContextT]
|
|
1313
|
+
):
|
|
1314
|
+
"""Create middleware with `wrap_model_call` hook from a function.
|
|
1315
|
+
|
|
1316
|
+
Converts a function with handler callback into middleware that can intercept
|
|
1317
|
+
model calls, implement retry logic, handle errors, and rewrite responses.
|
|
1318
|
+
|
|
1319
|
+
Args:
|
|
1320
|
+
func: Function accepting (request, handler) that calls handler(request)
|
|
1321
|
+
to execute the model and returns `ModelResponse` or `AIMessage`.
|
|
1322
|
+
Request contains state and runtime.
|
|
1323
|
+
state_schema: Custom state schema. Defaults to `AgentState`.
|
|
1324
|
+
tools: Additional tools to register with this middleware.
|
|
1325
|
+
name: Middleware class name. Defaults to function name.
|
|
1326
|
+
|
|
1327
|
+
Returns:
|
|
1328
|
+
`AgentMiddleware` instance if func provided, otherwise a decorator.
|
|
1329
|
+
|
|
1330
|
+
Examples:
|
|
1331
|
+
Basic retry logic:
|
|
1332
|
+
```python
|
|
1333
|
+
@wrap_model_call
|
|
1334
|
+
def retry_on_error(request, handler):
|
|
1335
|
+
max_retries = 3
|
|
1336
|
+
for attempt in range(max_retries):
|
|
1337
|
+
try:
|
|
1338
|
+
return handler(request)
|
|
1339
|
+
except Exception:
|
|
1340
|
+
if attempt == max_retries - 1:
|
|
1341
|
+
raise
|
|
1342
|
+
```
|
|
1343
|
+
|
|
1344
|
+
Model fallback:
|
|
1345
|
+
```python
|
|
1346
|
+
@wrap_model_call
|
|
1347
|
+
def fallback_model(request, handler):
|
|
1348
|
+
# Try primary model
|
|
1349
|
+
try:
|
|
1350
|
+
return handler(request)
|
|
1351
|
+
except Exception:
|
|
1352
|
+
pass
|
|
1353
|
+
|
|
1354
|
+
# Try fallback model
|
|
1355
|
+
request.model = fallback_model_instance
|
|
1356
|
+
return handler(request)
|
|
1357
|
+
```
|
|
1358
|
+
|
|
1359
|
+
Rewrite response content (full ModelResponse):
|
|
1360
|
+
```python
|
|
1361
|
+
@wrap_model_call
|
|
1362
|
+
def uppercase_responses(request, handler):
|
|
1363
|
+
response = handler(request)
|
|
1364
|
+
ai_msg = response.result[0]
|
|
1365
|
+
return ModelResponse(
|
|
1366
|
+
result=[AIMessage(content=ai_msg.content.upper())],
|
|
1367
|
+
structured_response=response.structured_response,
|
|
1368
|
+
)
|
|
1369
|
+
```
|
|
1370
|
+
|
|
1371
|
+
Simple AIMessage return (converted automatically):
|
|
1372
|
+
```python
|
|
1373
|
+
@wrap_model_call
|
|
1374
|
+
def simple_response(request, handler):
|
|
1375
|
+
# AIMessage is automatically converted to ModelResponse
|
|
1376
|
+
return AIMessage(content="Simple response")
|
|
1377
|
+
```
|
|
1378
|
+
"""
|
|
1379
|
+
|
|
1380
|
+
def decorator(
|
|
1381
|
+
func: _CallableReturningModelResponse[StateT, ContextT],
|
|
1382
|
+
) -> AgentMiddleware[StateT, ContextT]:
|
|
1383
|
+
is_async = iscoroutinefunction(func)
|
|
1384
|
+
|
|
1385
|
+
if is_async:
|
|
1386
|
+
|
|
1387
|
+
async def async_wrapped(
|
|
1388
|
+
self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
|
|
1389
|
+
request: ModelRequest,
|
|
1390
|
+
handler: Callable[[ModelRequest], Awaitable[ModelResponse]],
|
|
1391
|
+
) -> ModelCallResult:
|
|
1392
|
+
return await func(request, handler) # type: ignore[misc, arg-type]
|
|
1393
|
+
|
|
1394
|
+
middleware_name = name or cast(
|
|
1395
|
+
"str", getattr(func, "__name__", "WrapModelCallMiddleware")
|
|
1396
|
+
)
|
|
1397
|
+
|
|
1398
|
+
return type(
|
|
1399
|
+
middleware_name,
|
|
1400
|
+
(AgentMiddleware,),
|
|
1401
|
+
{
|
|
1402
|
+
"state_schema": state_schema or AgentState,
|
|
1403
|
+
"tools": tools or [],
|
|
1404
|
+
"awrap_model_call": async_wrapped,
|
|
1405
|
+
},
|
|
1406
|
+
)()
|
|
1407
|
+
|
|
1408
|
+
def wrapped(
|
|
1409
|
+
self: AgentMiddleware[StateT, ContextT], # noqa: ARG001
|
|
1410
|
+
request: ModelRequest,
|
|
1411
|
+
handler: Callable[[ModelRequest], ModelResponse],
|
|
1412
|
+
) -> ModelCallResult:
|
|
1413
|
+
return func(request, handler)
|
|
1414
|
+
|
|
1415
|
+
middleware_name = name or cast("str", getattr(func, "__name__", "WrapModelCallMiddleware"))
|
|
1416
|
+
|
|
1417
|
+
return type(
|
|
1418
|
+
middleware_name,
|
|
1419
|
+
(AgentMiddleware,),
|
|
1420
|
+
{
|
|
1421
|
+
"state_schema": state_schema or AgentState,
|
|
1422
|
+
"tools": tools or [],
|
|
1423
|
+
"wrap_model_call": wrapped,
|
|
1424
|
+
},
|
|
1425
|
+
)()
|
|
1426
|
+
|
|
1427
|
+
if func is not None:
|
|
1428
|
+
return decorator(func)
|
|
1429
|
+
return decorator
|
|
1430
|
+
|
|
1431
|
+
|
|
1432
|
+
@overload
|
|
1433
|
+
def wrap_tool_call(
|
|
1434
|
+
func: _CallableReturningToolResponse,
|
|
1435
|
+
) -> AgentMiddleware: ...
|
|
1436
|
+
|
|
1437
|
+
|
|
1438
|
+
@overload
|
|
1439
|
+
def wrap_tool_call(
|
|
1440
|
+
func: None = None,
|
|
1441
|
+
*,
|
|
1442
|
+
tools: list[BaseTool] | None = None,
|
|
1443
|
+
name: str | None = None,
|
|
1444
|
+
) -> Callable[
|
|
1445
|
+
[_CallableReturningToolResponse],
|
|
1446
|
+
AgentMiddleware,
|
|
1447
|
+
]: ...
|
|
1448
|
+
|
|
1449
|
+
|
|
1450
|
+
def wrap_tool_call(
|
|
1451
|
+
func: _CallableReturningToolResponse | None = None,
|
|
1452
|
+
*,
|
|
1453
|
+
tools: list[BaseTool] | None = None,
|
|
1454
|
+
name: str | None = None,
|
|
1455
|
+
) -> (
|
|
1456
|
+
Callable[
|
|
1457
|
+
[_CallableReturningToolResponse],
|
|
1458
|
+
AgentMiddleware,
|
|
1459
|
+
]
|
|
1460
|
+
| AgentMiddleware
|
|
1461
|
+
):
|
|
1462
|
+
"""Create middleware with `wrap_tool_call` hook from a function.
|
|
1463
|
+
|
|
1464
|
+
Converts a function with handler callback into middleware that can intercept
|
|
1465
|
+
tool calls, implement retry logic, monitor execution, and modify responses.
|
|
1466
|
+
|
|
1467
|
+
Args:
|
|
1468
|
+
func: Function accepting (request, handler) that calls
|
|
1469
|
+
handler(request) to execute the tool and returns final `ToolMessage` or
|
|
1470
|
+
`Command`. Can be sync or async.
|
|
1471
|
+
tools: Additional tools to register with this middleware.
|
|
1472
|
+
name: Middleware class name. Defaults to function name.
|
|
1473
|
+
|
|
1474
|
+
Returns:
|
|
1475
|
+
`AgentMiddleware` instance if func provided, otherwise a decorator.
|
|
1476
|
+
|
|
1477
|
+
Examples:
|
|
1478
|
+
Retry logic:
|
|
1479
|
+
```python
|
|
1480
|
+
@wrap_tool_call
|
|
1481
|
+
def retry_on_error(request, handler):
|
|
1482
|
+
max_retries = 3
|
|
1483
|
+
for attempt in range(max_retries):
|
|
1484
|
+
try:
|
|
1485
|
+
return handler(request)
|
|
1486
|
+
except Exception:
|
|
1487
|
+
if attempt == max_retries - 1:
|
|
1488
|
+
raise
|
|
1489
|
+
```
|
|
1490
|
+
|
|
1491
|
+
Async retry logic:
|
|
1492
|
+
```python
|
|
1493
|
+
@wrap_tool_call
|
|
1494
|
+
async def async_retry(request, handler):
|
|
1495
|
+
for attempt in range(3):
|
|
1496
|
+
try:
|
|
1497
|
+
return await handler(request)
|
|
1498
|
+
except Exception:
|
|
1499
|
+
if attempt == 2:
|
|
1500
|
+
raise
|
|
1501
|
+
```
|
|
1502
|
+
|
|
1503
|
+
Modify request:
|
|
1504
|
+
```python
|
|
1505
|
+
@wrap_tool_call
|
|
1506
|
+
def modify_args(request, handler):
|
|
1507
|
+
request.tool_call["args"]["value"] *= 2
|
|
1508
|
+
return handler(request)
|
|
1509
|
+
```
|
|
1510
|
+
|
|
1511
|
+
Short-circuit with cached result:
|
|
1512
|
+
```python
|
|
1513
|
+
@wrap_tool_call
|
|
1514
|
+
def with_cache(request, handler):
|
|
1515
|
+
if cached := get_cache(request):
|
|
1516
|
+
return ToolMessage(content=cached, tool_call_id=request.tool_call["id"])
|
|
1517
|
+
result = handler(request)
|
|
1518
|
+
save_cache(request, result)
|
|
1519
|
+
return result
|
|
1520
|
+
```
|
|
1521
|
+
"""
|
|
1522
|
+
|
|
1523
|
+
def decorator(
|
|
1524
|
+
func: _CallableReturningToolResponse,
|
|
1525
|
+
) -> AgentMiddleware:
|
|
1526
|
+
is_async = iscoroutinefunction(func)
|
|
1527
|
+
|
|
1528
|
+
if is_async:
|
|
1529
|
+
|
|
1530
|
+
async def async_wrapped(
|
|
1531
|
+
self: AgentMiddleware, # noqa: ARG001
|
|
1532
|
+
request: ToolCallRequest,
|
|
1533
|
+
handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command]],
|
|
1534
|
+
) -> ToolMessage | Command:
|
|
1535
|
+
return await func(request, handler) # type: ignore[arg-type,misc]
|
|
1536
|
+
|
|
1537
|
+
middleware_name = name or cast(
|
|
1538
|
+
"str", getattr(func, "__name__", "WrapToolCallMiddleware")
|
|
1539
|
+
)
|
|
1540
|
+
|
|
1541
|
+
return type(
|
|
1542
|
+
middleware_name,
|
|
1543
|
+
(AgentMiddleware,),
|
|
1544
|
+
{
|
|
1545
|
+
"state_schema": AgentState,
|
|
1546
|
+
"tools": tools or [],
|
|
1547
|
+
"awrap_tool_call": async_wrapped,
|
|
1548
|
+
},
|
|
1549
|
+
)()
|
|
1550
|
+
|
|
1551
|
+
def wrapped(
|
|
1552
|
+
self: AgentMiddleware, # noqa: ARG001
|
|
1553
|
+
request: ToolCallRequest,
|
|
1554
|
+
handler: Callable[[ToolCallRequest], ToolMessage | Command],
|
|
1555
|
+
) -> ToolMessage | Command:
|
|
1556
|
+
return func(request, handler)
|
|
1557
|
+
|
|
1558
|
+
middleware_name = name or cast("str", getattr(func, "__name__", "WrapToolCallMiddleware"))
|
|
1559
|
+
|
|
1560
|
+
return type(
|
|
1561
|
+
middleware_name,
|
|
1562
|
+
(AgentMiddleware,),
|
|
1563
|
+
{
|
|
1564
|
+
"state_schema": AgentState,
|
|
1565
|
+
"tools": tools or [],
|
|
1566
|
+
"wrap_tool_call": wrapped,
|
|
1567
|
+
},
|
|
1568
|
+
)()
|
|
1569
|
+
|
|
1570
|
+
if func is not None:
|
|
1571
|
+
return decorator(func)
|
|
1572
|
+
return decorator
|