langchain 0.3.22__py3-none-any.whl → 0.3.24__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.
- langchain/_api/module_import.py +3 -3
- langchain/agents/agent.py +104 -109
- langchain/agents/agent_iterator.py +11 -15
- langchain/agents/agent_toolkits/conversational_retrieval/openai_functions.py +2 -2
- langchain/agents/agent_toolkits/vectorstore/base.py +3 -3
- langchain/agents/agent_toolkits/vectorstore/toolkit.py +4 -6
- langchain/agents/chat/base.py +7 -6
- langchain/agents/chat/output_parser.py +2 -1
- langchain/agents/conversational/base.py +5 -4
- langchain/agents/conversational_chat/base.py +9 -8
- langchain/agents/format_scratchpad/log.py +1 -3
- langchain/agents/format_scratchpad/log_to_messages.py +3 -5
- langchain/agents/format_scratchpad/openai_functions.py +4 -4
- langchain/agents/format_scratchpad/tools.py +3 -3
- langchain/agents/format_scratchpad/xml.py +1 -3
- langchain/agents/initialize.py +2 -1
- langchain/agents/json_chat/base.py +3 -2
- langchain/agents/loading.py +5 -5
- langchain/agents/mrkl/base.py +6 -5
- langchain/agents/openai_assistant/base.py +13 -17
- langchain/agents/openai_functions_agent/agent_token_buffer_memory.py +6 -6
- langchain/agents/openai_functions_agent/base.py +13 -12
- langchain/agents/openai_functions_multi_agent/base.py +15 -14
- langchain/agents/openai_tools/base.py +2 -1
- langchain/agents/output_parsers/openai_functions.py +2 -2
- langchain/agents/output_parsers/openai_tools.py +6 -6
- langchain/agents/output_parsers/react_json_single_input.py +2 -1
- langchain/agents/output_parsers/self_ask.py +2 -1
- langchain/agents/output_parsers/tools.py +7 -7
- langchain/agents/react/agent.py +3 -2
- langchain/agents/react/base.py +4 -3
- langchain/agents/schema.py +3 -3
- langchain/agents/self_ask_with_search/base.py +2 -1
- langchain/agents/structured_chat/base.py +9 -8
- langchain/agents/structured_chat/output_parser.py +2 -1
- langchain/agents/tool_calling_agent/base.py +3 -2
- langchain/agents/tools.py +4 -4
- langchain/agents/types.py +3 -3
- langchain/agents/utils.py +1 -1
- langchain/agents/xml/base.py +7 -6
- langchain/callbacks/streaming_aiter.py +3 -2
- langchain/callbacks/streaming_aiter_final_only.py +3 -3
- langchain/callbacks/streaming_stdout_final_only.py +3 -3
- langchain/chains/api/base.py +11 -12
- langchain/chains/base.py +47 -50
- langchain/chains/combine_documents/base.py +23 -23
- langchain/chains/combine_documents/map_reduce.py +12 -12
- langchain/chains/combine_documents/map_rerank.py +16 -15
- langchain/chains/combine_documents/reduce.py +17 -17
- langchain/chains/combine_documents/refine.py +12 -12
- langchain/chains/combine_documents/stuff.py +10 -10
- langchain/chains/constitutional_ai/base.py +9 -9
- langchain/chains/conversation/base.py +2 -4
- langchain/chains/conversational_retrieval/base.py +30 -30
- langchain/chains/elasticsearch_database/base.py +13 -13
- langchain/chains/example_generator.py +1 -3
- langchain/chains/flare/base.py +13 -12
- langchain/chains/flare/prompts.py +2 -4
- langchain/chains/hyde/base.py +8 -8
- langchain/chains/llm.py +31 -30
- langchain/chains/llm_checker/base.py +6 -6
- langchain/chains/llm_math/base.py +10 -10
- langchain/chains/llm_summarization_checker/base.py +6 -6
- langchain/chains/loading.py +12 -14
- langchain/chains/mapreduce.py +7 -6
- langchain/chains/moderation.py +8 -8
- langchain/chains/natbot/base.py +6 -6
- langchain/chains/openai_functions/base.py +8 -10
- langchain/chains/openai_functions/citation_fuzzy_match.py +4 -4
- langchain/chains/openai_functions/extraction.py +3 -3
- langchain/chains/openai_functions/openapi.py +12 -12
- langchain/chains/openai_functions/qa_with_structure.py +4 -4
- langchain/chains/openai_functions/utils.py +2 -2
- langchain/chains/openai_tools/extraction.py +2 -2
- langchain/chains/prompt_selector.py +3 -3
- langchain/chains/qa_generation/base.py +5 -5
- langchain/chains/qa_with_sources/base.py +21 -21
- langchain/chains/qa_with_sources/loading.py +2 -1
- langchain/chains/qa_with_sources/retrieval.py +6 -6
- langchain/chains/qa_with_sources/vector_db.py +8 -8
- langchain/chains/query_constructor/base.py +4 -3
- langchain/chains/query_constructor/parser.py +5 -4
- langchain/chains/question_answering/chain.py +3 -2
- langchain/chains/retrieval.py +2 -2
- langchain/chains/retrieval_qa/base.py +16 -16
- langchain/chains/router/base.py +12 -11
- langchain/chains/router/embedding_router.py +12 -11
- langchain/chains/router/llm_router.py +12 -12
- langchain/chains/router/multi_prompt.py +3 -3
- langchain/chains/router/multi_retrieval_qa.py +5 -4
- langchain/chains/sequential.py +18 -18
- langchain/chains/sql_database/query.py +4 -4
- langchain/chains/structured_output/base.py +14 -13
- langchain/chains/summarize/chain.py +4 -3
- langchain/chains/transform.py +12 -11
- langchain/chat_models/base.py +34 -31
- langchain/embeddings/__init__.py +1 -1
- langchain/embeddings/base.py +4 -4
- langchain/embeddings/cache.py +19 -18
- langchain/evaluation/agents/trajectory_eval_chain.py +16 -19
- langchain/evaluation/comparison/eval_chain.py +10 -10
- langchain/evaluation/criteria/eval_chain.py +11 -10
- langchain/evaluation/embedding_distance/base.py +21 -21
- langchain/evaluation/exact_match/base.py +3 -3
- langchain/evaluation/loading.py +7 -8
- langchain/evaluation/qa/eval_chain.py +7 -6
- langchain/evaluation/regex_match/base.py +3 -3
- langchain/evaluation/schema.py +6 -5
- langchain/evaluation/scoring/eval_chain.py +9 -9
- langchain/evaluation/string_distance/base.py +23 -23
- langchain/hub.py +2 -1
- langchain/indexes/_sql_record_manager.py +8 -7
- langchain/indexes/vectorstore.py +11 -11
- langchain/llms/__init__.py +3 -3
- langchain/memory/buffer.py +13 -13
- langchain/memory/buffer_window.py +5 -5
- langchain/memory/chat_memory.py +5 -5
- langchain/memory/combined.py +10 -10
- langchain/memory/entity.py +8 -7
- langchain/memory/readonly.py +4 -4
- langchain/memory/simple.py +5 -5
- langchain/memory/summary.py +8 -8
- langchain/memory/summary_buffer.py +11 -11
- langchain/memory/token_buffer.py +5 -5
- langchain/memory/utils.py +2 -2
- langchain/memory/vectorstore.py +15 -14
- langchain/memory/vectorstore_token_buffer_memory.py +7 -7
- langchain/model_laboratory.py +4 -3
- langchain/output_parsers/combining.py +5 -5
- langchain/output_parsers/datetime.py +1 -2
- langchain/output_parsers/enum.py +4 -5
- langchain/output_parsers/pandas_dataframe.py +5 -5
- langchain/output_parsers/regex.py +4 -4
- langchain/output_parsers/regex_dict.py +4 -4
- langchain/output_parsers/retry.py +2 -2
- langchain/output_parsers/structured.py +5 -5
- langchain/output_parsers/yaml.py +3 -3
- langchain/pydantic_v1/__init__.py +1 -6
- langchain/pydantic_v1/dataclasses.py +1 -5
- langchain/pydantic_v1/main.py +1 -5
- langchain/retrievers/contextual_compression.py +3 -3
- langchain/retrievers/document_compressors/base.py +3 -2
- langchain/retrievers/document_compressors/chain_extract.py +4 -3
- langchain/retrievers/document_compressors/chain_filter.py +3 -2
- langchain/retrievers/document_compressors/cohere_rerank.py +4 -3
- langchain/retrievers/document_compressors/cross_encoder.py +1 -2
- langchain/retrievers/document_compressors/cross_encoder_rerank.py +2 -1
- langchain/retrievers/document_compressors/embeddings_filter.py +3 -2
- langchain/retrievers/document_compressors/listwise_rerank.py +6 -5
- langchain/retrievers/ensemble.py +15 -19
- langchain/retrievers/merger_retriever.py +7 -12
- langchain/retrievers/multi_query.py +14 -13
- langchain/retrievers/multi_vector.py +4 -4
- langchain/retrievers/parent_document_retriever.py +9 -8
- langchain/retrievers/re_phraser.py +2 -3
- langchain/retrievers/self_query/base.py +13 -12
- langchain/retrievers/time_weighted_retriever.py +14 -14
- langchain/runnables/openai_functions.py +4 -3
- langchain/smith/evaluation/config.py +7 -6
- langchain/smith/evaluation/progress.py +3 -2
- langchain/smith/evaluation/runner_utils.py +58 -61
- langchain/smith/evaluation/string_run_evaluator.py +29 -29
- langchain/storage/encoder_backed.py +7 -11
- langchain/storage/file_system.py +5 -4
- {langchain-0.3.22.dist-info → langchain-0.3.24.dist-info}/METADATA +5 -3
- {langchain-0.3.22.dist-info → langchain-0.3.24.dist-info}/RECORD +169 -169
- {langchain-0.3.22.dist-info → langchain-0.3.24.dist-info}/WHEEL +1 -1
- langchain-0.3.24.dist-info/entry_points.txt +4 -0
- langchain-0.3.22.dist-info/entry_points.txt +0 -5
- {langchain-0.3.22.dist-info → langchain-0.3.24.dist-info}/licenses/LICENSE +0 -0
|
@@ -3,15 +3,11 @@ from __future__ import annotations
|
|
|
3
3
|
import asyncio
|
|
4
4
|
import logging
|
|
5
5
|
import time
|
|
6
|
+
from collections.abc import AsyncIterator, Iterator
|
|
6
7
|
from typing import (
|
|
7
8
|
TYPE_CHECKING,
|
|
8
9
|
Any,
|
|
9
|
-
AsyncIterator,
|
|
10
|
-
Dict,
|
|
11
|
-
Iterator,
|
|
12
|
-
List,
|
|
13
10
|
Optional,
|
|
14
|
-
Tuple,
|
|
15
11
|
Union,
|
|
16
12
|
)
|
|
17
13
|
from uuid import UUID
|
|
@@ -53,7 +49,7 @@ class AgentExecutorIterator:
|
|
|
53
49
|
callbacks: Callbacks = None,
|
|
54
50
|
*,
|
|
55
51
|
tags: Optional[list[str]] = None,
|
|
56
|
-
metadata: Optional[
|
|
52
|
+
metadata: Optional[dict[str, Any]] = None,
|
|
57
53
|
run_name: Optional[str] = None,
|
|
58
54
|
run_id: Optional[UUID] = None,
|
|
59
55
|
include_run_info: bool = False,
|
|
@@ -90,17 +86,17 @@ class AgentExecutorIterator:
|
|
|
90
86
|
self.yield_actions = yield_actions
|
|
91
87
|
self.reset()
|
|
92
88
|
|
|
93
|
-
_inputs:
|
|
89
|
+
_inputs: dict[str, str]
|
|
94
90
|
callbacks: Callbacks
|
|
95
91
|
tags: Optional[list[str]]
|
|
96
|
-
metadata: Optional[
|
|
92
|
+
metadata: Optional[dict[str, Any]]
|
|
97
93
|
run_name: Optional[str]
|
|
98
94
|
run_id: Optional[UUID]
|
|
99
95
|
include_run_info: bool
|
|
100
96
|
yield_actions: bool
|
|
101
97
|
|
|
102
98
|
@property
|
|
103
|
-
def inputs(self) ->
|
|
99
|
+
def inputs(self) -> dict[str, str]:
|
|
104
100
|
"""The inputs to the AgentExecutor."""
|
|
105
101
|
return self._inputs
|
|
106
102
|
|
|
@@ -120,12 +116,12 @@ class AgentExecutorIterator:
|
|
|
120
116
|
self.inputs = self.inputs
|
|
121
117
|
|
|
122
118
|
@property
|
|
123
|
-
def name_to_tool_map(self) ->
|
|
119
|
+
def name_to_tool_map(self) -> dict[str, BaseTool]:
|
|
124
120
|
"""A mapping of tool names to tools."""
|
|
125
121
|
return {tool.name: tool for tool in self.agent_executor.tools}
|
|
126
122
|
|
|
127
123
|
@property
|
|
128
|
-
def color_mapping(self) ->
|
|
124
|
+
def color_mapping(self) -> dict[str, str]:
|
|
129
125
|
"""A mapping of tool names to colors."""
|
|
130
126
|
return get_color_mapping(
|
|
131
127
|
[tool.name for tool in self.agent_executor.tools],
|
|
@@ -156,7 +152,7 @@ class AgentExecutorIterator:
|
|
|
156
152
|
|
|
157
153
|
def make_final_outputs(
|
|
158
154
|
self,
|
|
159
|
-
outputs:
|
|
155
|
+
outputs: dict[str, Any],
|
|
160
156
|
run_manager: Union[CallbackManagerForChainRun, AsyncCallbackManagerForChainRun],
|
|
161
157
|
) -> AddableDict:
|
|
162
158
|
# have access to intermediate steps by design in iterator,
|
|
@@ -171,7 +167,7 @@ class AgentExecutorIterator:
|
|
|
171
167
|
prepared_outputs[RUN_KEY] = RunInfo(run_id=run_manager.run_id)
|
|
172
168
|
return prepared_outputs
|
|
173
169
|
|
|
174
|
-
def __iter__(self:
|
|
170
|
+
def __iter__(self: AgentExecutorIterator) -> Iterator[AddableDict]:
|
|
175
171
|
logger.debug("Initialising AgentExecutorIterator")
|
|
176
172
|
self.reset()
|
|
177
173
|
callback_manager = CallbackManager.configure(
|
|
@@ -311,7 +307,7 @@ class AgentExecutorIterator:
|
|
|
311
307
|
|
|
312
308
|
def _process_next_step_output(
|
|
313
309
|
self,
|
|
314
|
-
next_step_output: Union[AgentFinish,
|
|
310
|
+
next_step_output: Union[AgentFinish, list[tuple[AgentAction, str]]],
|
|
315
311
|
run_manager: CallbackManagerForChainRun,
|
|
316
312
|
) -> AddableDict:
|
|
317
313
|
"""
|
|
@@ -339,7 +335,7 @@ class AgentExecutorIterator:
|
|
|
339
335
|
|
|
340
336
|
async def _aprocess_next_step_output(
|
|
341
337
|
self,
|
|
342
|
-
next_step_output: Union[AgentFinish,
|
|
338
|
+
next_step_output: Union[AgentFinish, list[tuple[AgentAction, str]]],
|
|
343
339
|
run_manager: AsyncCallbackManagerForChainRun,
|
|
344
340
|
) -> AddableDict:
|
|
345
341
|
"""
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
from typing import Any,
|
|
1
|
+
from typing import Any, Optional
|
|
2
2
|
|
|
3
3
|
from langchain_core.language_models import BaseLanguageModel
|
|
4
4
|
from langchain_core.memory import BaseMemory
|
|
@@ -26,7 +26,7 @@ def _get_default_system_message() -> SystemMessage:
|
|
|
26
26
|
|
|
27
27
|
def create_conversational_retrieval_agent(
|
|
28
28
|
llm: BaseLanguageModel,
|
|
29
|
-
tools:
|
|
29
|
+
tools: list[BaseTool],
|
|
30
30
|
remember_intermediate_steps: bool = True,
|
|
31
31
|
memory_key: str = "chat_history",
|
|
32
32
|
system_message: Optional[SystemMessage] = None,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""VectorStore agent."""
|
|
2
2
|
|
|
3
|
-
from typing import Any,
|
|
3
|
+
from typing import Any, Optional
|
|
4
4
|
|
|
5
5
|
from langchain_core._api import deprecated
|
|
6
6
|
from langchain_core.callbacks.base import BaseCallbackManager
|
|
@@ -36,7 +36,7 @@ def create_vectorstore_agent(
|
|
|
36
36
|
callback_manager: Optional[BaseCallbackManager] = None,
|
|
37
37
|
prefix: str = PREFIX,
|
|
38
38
|
verbose: bool = False,
|
|
39
|
-
agent_executor_kwargs: Optional[
|
|
39
|
+
agent_executor_kwargs: Optional[dict[str, Any]] = None,
|
|
40
40
|
**kwargs: Any,
|
|
41
41
|
) -> AgentExecutor:
|
|
42
42
|
"""Construct a VectorStore agent from an LLM and tools.
|
|
@@ -129,7 +129,7 @@ def create_vectorstore_router_agent(
|
|
|
129
129
|
callback_manager: Optional[BaseCallbackManager] = None,
|
|
130
130
|
prefix: str = ROUTER_PREFIX,
|
|
131
131
|
verbose: bool = False,
|
|
132
|
-
agent_executor_kwargs: Optional[
|
|
132
|
+
agent_executor_kwargs: Optional[dict[str, Any]] = None,
|
|
133
133
|
**kwargs: Any,
|
|
134
134
|
) -> AgentExecutor:
|
|
135
135
|
"""Construct a VectorStore router agent from an LLM and tools.
|
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
"""Toolkit for interacting with a vector store."""
|
|
2
2
|
|
|
3
|
-
from typing import List
|
|
4
|
-
|
|
5
3
|
from langchain_core.language_models import BaseLanguageModel
|
|
6
4
|
from langchain_core.tools import BaseTool
|
|
7
5
|
from langchain_core.tools.base import BaseToolkit
|
|
@@ -31,7 +29,7 @@ class VectorStoreToolkit(BaseToolkit):
|
|
|
31
29
|
arbitrary_types_allowed=True,
|
|
32
30
|
)
|
|
33
31
|
|
|
34
|
-
def get_tools(self) ->
|
|
32
|
+
def get_tools(self) -> list[BaseTool]:
|
|
35
33
|
"""Get the tools in the toolkit."""
|
|
36
34
|
try:
|
|
37
35
|
from langchain_community.tools.vectorstore.tool import (
|
|
@@ -66,16 +64,16 @@ class VectorStoreToolkit(BaseToolkit):
|
|
|
66
64
|
class VectorStoreRouterToolkit(BaseToolkit):
|
|
67
65
|
"""Toolkit for routing between Vector Stores."""
|
|
68
66
|
|
|
69
|
-
vectorstores:
|
|
67
|
+
vectorstores: list[VectorStoreInfo] = Field(exclude=True)
|
|
70
68
|
llm: BaseLanguageModel
|
|
71
69
|
|
|
72
70
|
model_config = ConfigDict(
|
|
73
71
|
arbitrary_types_allowed=True,
|
|
74
72
|
)
|
|
75
73
|
|
|
76
|
-
def get_tools(self) ->
|
|
74
|
+
def get_tools(self) -> list[BaseTool]:
|
|
77
75
|
"""Get the tools in the toolkit."""
|
|
78
|
-
tools:
|
|
76
|
+
tools: list[BaseTool] = []
|
|
79
77
|
try:
|
|
80
78
|
from langchain_community.tools.vectorstore.tool import (
|
|
81
79
|
VectorStoreQATool,
|
langchain/agents/chat/base.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
from
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
from typing import Any, Optional
|
|
2
3
|
|
|
3
4
|
from langchain_core._api import deprecated
|
|
4
5
|
from langchain_core.agents import AgentAction
|
|
@@ -48,7 +49,7 @@ class ChatAgent(Agent):
|
|
|
48
49
|
return "Thought:"
|
|
49
50
|
|
|
50
51
|
def _construct_scratchpad(
|
|
51
|
-
self, intermediate_steps:
|
|
52
|
+
self, intermediate_steps: list[tuple[AgentAction, str]]
|
|
52
53
|
) -> str:
|
|
53
54
|
agent_scratchpad = super()._construct_scratchpad(intermediate_steps)
|
|
54
55
|
if not isinstance(agent_scratchpad, str):
|
|
@@ -72,7 +73,7 @@ class ChatAgent(Agent):
|
|
|
72
73
|
validate_tools_single_input(class_name=cls.__name__, tools=tools)
|
|
73
74
|
|
|
74
75
|
@property
|
|
75
|
-
def _stop(self) ->
|
|
76
|
+
def _stop(self) -> list[str]:
|
|
76
77
|
return ["Observation:"]
|
|
77
78
|
|
|
78
79
|
@classmethod
|
|
@@ -83,7 +84,7 @@ class ChatAgent(Agent):
|
|
|
83
84
|
system_message_suffix: str = SYSTEM_MESSAGE_SUFFIX,
|
|
84
85
|
human_message: str = HUMAN_MESSAGE,
|
|
85
86
|
format_instructions: str = FORMAT_INSTRUCTIONS,
|
|
86
|
-
input_variables: Optional[
|
|
87
|
+
input_variables: Optional[list[str]] = None,
|
|
87
88
|
) -> BasePromptTemplate:
|
|
88
89
|
"""Create a prompt from a list of tools.
|
|
89
90
|
|
|
@@ -119,7 +120,7 @@ class ChatAgent(Agent):
|
|
|
119
120
|
]
|
|
120
121
|
if input_variables is None:
|
|
121
122
|
input_variables = ["input", "agent_scratchpad"]
|
|
122
|
-
return ChatPromptTemplate(input_variables=input_variables, messages=messages)
|
|
123
|
+
return ChatPromptTemplate(input_variables=input_variables, messages=messages)
|
|
123
124
|
|
|
124
125
|
@classmethod
|
|
125
126
|
def from_llm_and_tools(
|
|
@@ -132,7 +133,7 @@ class ChatAgent(Agent):
|
|
|
132
133
|
system_message_suffix: str = SYSTEM_MESSAGE_SUFFIX,
|
|
133
134
|
human_message: str = HUMAN_MESSAGE,
|
|
134
135
|
format_instructions: str = FORMAT_INSTRUCTIONS,
|
|
135
|
-
input_variables: Optional[
|
|
136
|
+
input_variables: Optional[list[str]] = None,
|
|
136
137
|
**kwargs: Any,
|
|
137
138
|
) -> Agent:
|
|
138
139
|
"""Construct an agent from an LLM and tools.
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
from
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from typing import Any, Optional
|
|
6
7
|
|
|
7
8
|
from langchain_core._api import deprecated
|
|
8
9
|
from langchain_core.callbacks import BaseCallbackManager
|
|
@@ -71,7 +72,7 @@ class ConversationalAgent(Agent):
|
|
|
71
72
|
format_instructions: str = FORMAT_INSTRUCTIONS,
|
|
72
73
|
ai_prefix: str = "AI",
|
|
73
74
|
human_prefix: str = "Human",
|
|
74
|
-
input_variables: Optional[
|
|
75
|
+
input_variables: Optional[list[str]] = None,
|
|
75
76
|
) -> PromptTemplate:
|
|
76
77
|
"""Create prompt in the style of the zero-shot agent.
|
|
77
78
|
|
|
@@ -120,7 +121,7 @@ class ConversationalAgent(Agent):
|
|
|
120
121
|
format_instructions: str = FORMAT_INSTRUCTIONS,
|
|
121
122
|
ai_prefix: str = "AI",
|
|
122
123
|
human_prefix: str = "Human",
|
|
123
|
-
input_variables: Optional[
|
|
124
|
+
input_variables: Optional[list[str]] = None,
|
|
124
125
|
**kwargs: Any,
|
|
125
126
|
) -> Agent:
|
|
126
127
|
"""Construct an agent from an LLM and tools.
|
|
@@ -153,7 +154,7 @@ class ConversationalAgent(Agent):
|
|
|
153
154
|
format_instructions=format_instructions,
|
|
154
155
|
input_variables=input_variables,
|
|
155
156
|
)
|
|
156
|
-
llm_chain = LLMChain(
|
|
157
|
+
llm_chain = LLMChain(
|
|
157
158
|
llm=llm,
|
|
158
159
|
prompt=prompt,
|
|
159
160
|
callback_manager=callback_manager,
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
from
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from typing import Any, Optional
|
|
6
7
|
|
|
7
8
|
from langchain_core._api import deprecated
|
|
8
9
|
from langchain_core.agents import AgentAction
|
|
@@ -77,7 +78,7 @@ class ConversationalChatAgent(Agent):
|
|
|
77
78
|
tools: Sequence[BaseTool],
|
|
78
79
|
system_message: str = PREFIX,
|
|
79
80
|
human_message: str = SUFFIX,
|
|
80
|
-
input_variables: Optional[
|
|
81
|
+
input_variables: Optional[list[str]] = None,
|
|
81
82
|
output_parser: Optional[BaseOutputParser] = None,
|
|
82
83
|
) -> BasePromptTemplate:
|
|
83
84
|
"""Create a prompt for the agent.
|
|
@@ -113,13 +114,13 @@ class ConversationalChatAgent(Agent):
|
|
|
113
114
|
HumanMessagePromptTemplate.from_template(final_prompt),
|
|
114
115
|
MessagesPlaceholder(variable_name="agent_scratchpad"),
|
|
115
116
|
]
|
|
116
|
-
return ChatPromptTemplate(input_variables=input_variables, messages=messages)
|
|
117
|
+
return ChatPromptTemplate(input_variables=input_variables, messages=messages)
|
|
117
118
|
|
|
118
119
|
def _construct_scratchpad(
|
|
119
|
-
self, intermediate_steps:
|
|
120
|
-
) ->
|
|
120
|
+
self, intermediate_steps: list[tuple[AgentAction, str]]
|
|
121
|
+
) -> list[BaseMessage]:
|
|
121
122
|
"""Construct the scratchpad that lets the agent continue its thought process."""
|
|
122
|
-
thoughts:
|
|
123
|
+
thoughts: list[BaseMessage] = []
|
|
123
124
|
for action, observation in intermediate_steps:
|
|
124
125
|
thoughts.append(AIMessage(content=action.log))
|
|
125
126
|
human_message = HumanMessage(
|
|
@@ -137,7 +138,7 @@ class ConversationalChatAgent(Agent):
|
|
|
137
138
|
output_parser: Optional[AgentOutputParser] = None,
|
|
138
139
|
system_message: str = PREFIX,
|
|
139
140
|
human_message: str = SUFFIX,
|
|
140
|
-
input_variables: Optional[
|
|
141
|
+
input_variables: Optional[list[str]] = None,
|
|
141
142
|
**kwargs: Any,
|
|
142
143
|
) -> Agent:
|
|
143
144
|
"""Construct an agent from an LLM and tools.
|
|
@@ -164,7 +165,7 @@ class ConversationalChatAgent(Agent):
|
|
|
164
165
|
input_variables=input_variables,
|
|
165
166
|
output_parser=_output_parser,
|
|
166
167
|
)
|
|
167
|
-
llm_chain = LLMChain(
|
|
168
|
+
llm_chain = LLMChain(
|
|
168
169
|
llm=llm,
|
|
169
170
|
prompt=prompt,
|
|
170
171
|
callback_manager=callback_manager,
|
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
from typing import List, Tuple
|
|
2
|
-
|
|
3
1
|
from langchain_core.agents import AgentAction
|
|
4
2
|
|
|
5
3
|
|
|
6
4
|
def format_log_to_str(
|
|
7
|
-
intermediate_steps:
|
|
5
|
+
intermediate_steps: list[tuple[AgentAction, str]],
|
|
8
6
|
observation_prefix: str = "Observation: ",
|
|
9
7
|
llm_prefix: str = "Thought: ",
|
|
10
8
|
) -> str:
|
|
@@ -1,13 +1,11 @@
|
|
|
1
|
-
from typing import List, Tuple
|
|
2
|
-
|
|
3
1
|
from langchain_core.agents import AgentAction
|
|
4
2
|
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
|
|
5
3
|
|
|
6
4
|
|
|
7
5
|
def format_log_to_messages(
|
|
8
|
-
intermediate_steps:
|
|
6
|
+
intermediate_steps: list[tuple[AgentAction, str]],
|
|
9
7
|
template_tool_response: str = "{observation}",
|
|
10
|
-
) ->
|
|
8
|
+
) -> list[BaseMessage]:
|
|
11
9
|
"""Construct the scratchpad that lets the agent continue its thought process.
|
|
12
10
|
|
|
13
11
|
Args:
|
|
@@ -18,7 +16,7 @@ def format_log_to_messages(
|
|
|
18
16
|
Returns:
|
|
19
17
|
List[BaseMessage]: The scratchpad.
|
|
20
18
|
"""
|
|
21
|
-
thoughts:
|
|
19
|
+
thoughts: list[BaseMessage] = []
|
|
22
20
|
for action, observation in intermediate_steps:
|
|
23
21
|
thoughts.append(AIMessage(content=action.log))
|
|
24
22
|
human_message = HumanMessage(
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import json
|
|
2
|
-
from
|
|
2
|
+
from collections.abc import Sequence
|
|
3
3
|
|
|
4
4
|
from langchain_core.agents import AgentAction, AgentActionMessageLog
|
|
5
5
|
from langchain_core.messages import AIMessage, BaseMessage, FunctionMessage
|
|
@@ -7,7 +7,7 @@ from langchain_core.messages import AIMessage, BaseMessage, FunctionMessage
|
|
|
7
7
|
|
|
8
8
|
def _convert_agent_action_to_messages(
|
|
9
9
|
agent_action: AgentAction, observation: str
|
|
10
|
-
) ->
|
|
10
|
+
) -> list[BaseMessage]:
|
|
11
11
|
"""Convert an agent action to a message.
|
|
12
12
|
|
|
13
13
|
This code is used to reconstruct the original AI message from the agent action.
|
|
@@ -54,8 +54,8 @@ def _create_function_message(
|
|
|
54
54
|
|
|
55
55
|
|
|
56
56
|
def format_to_openai_function_messages(
|
|
57
|
-
intermediate_steps: Sequence[
|
|
58
|
-
) ->
|
|
57
|
+
intermediate_steps: Sequence[tuple[AgentAction, str]],
|
|
58
|
+
) -> list[BaseMessage]:
|
|
59
59
|
"""Convert (AgentAction, tool output) tuples into FunctionMessages.
|
|
60
60
|
|
|
61
61
|
Args:
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import json
|
|
2
|
-
from
|
|
2
|
+
from collections.abc import Sequence
|
|
3
3
|
|
|
4
4
|
from langchain_core.agents import AgentAction
|
|
5
5
|
from langchain_core.messages import (
|
|
@@ -40,8 +40,8 @@ def _create_tool_message(
|
|
|
40
40
|
|
|
41
41
|
|
|
42
42
|
def format_to_tool_messages(
|
|
43
|
-
intermediate_steps: Sequence[
|
|
44
|
-
) ->
|
|
43
|
+
intermediate_steps: Sequence[tuple[AgentAction, str]],
|
|
44
|
+
) -> list[BaseMessage]:
|
|
45
45
|
"""Convert (AgentAction, tool output) tuples into ToolMessages.
|
|
46
46
|
|
|
47
47
|
Args:
|
|
@@ -1,10 +1,8 @@
|
|
|
1
|
-
from typing import List, Tuple
|
|
2
|
-
|
|
3
1
|
from langchain_core.agents import AgentAction
|
|
4
2
|
|
|
5
3
|
|
|
6
4
|
def format_xml(
|
|
7
|
-
intermediate_steps:
|
|
5
|
+
intermediate_steps: list[tuple[AgentAction, str]],
|
|
8
6
|
) -> str:
|
|
9
7
|
"""Format the intermediate steps as XML.
|
|
10
8
|
|
langchain/agents/initialize.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
from
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
from typing import Union
|
|
2
3
|
|
|
3
4
|
from langchain_core.language_models import BaseLanguageModel
|
|
4
5
|
from langchain_core.prompts.chat import ChatPromptTemplate
|
|
@@ -15,7 +16,7 @@ def create_json_chat_agent(
|
|
|
15
16
|
llm: BaseLanguageModel,
|
|
16
17
|
tools: Sequence[BaseTool],
|
|
17
18
|
prompt: ChatPromptTemplate,
|
|
18
|
-
stop_sequence: Union[bool,
|
|
19
|
+
stop_sequence: Union[bool, list[str]] = True,
|
|
19
20
|
tools_renderer: ToolsRenderer = render_text_description,
|
|
20
21
|
template_tool_response: str = TEMPLATE_TOOL_RESPONSE,
|
|
21
22
|
) -> Runnable:
|
langchain/agents/loading.py
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import json
|
|
4
4
|
import logging
|
|
5
5
|
from pathlib import Path
|
|
6
|
-
from typing import Any,
|
|
6
|
+
from typing import Any, Optional, Union
|
|
7
7
|
|
|
8
8
|
import yaml
|
|
9
9
|
from langchain_core._api import deprecated
|
|
@@ -20,7 +20,7 @@ URL_BASE = "https://raw.githubusercontent.com/hwchase17/langchain-hub/master/age
|
|
|
20
20
|
|
|
21
21
|
|
|
22
22
|
def _load_agent_from_tools(
|
|
23
|
-
config: dict, llm: BaseLanguageModel, tools:
|
|
23
|
+
config: dict, llm: BaseLanguageModel, tools: list[Tool], **kwargs: Any
|
|
24
24
|
) -> Union[BaseSingleActionAgent, BaseMultiActionAgent]:
|
|
25
25
|
config_type = config.pop("_type")
|
|
26
26
|
if config_type not in AGENT_TO_CLASS:
|
|
@@ -35,7 +35,7 @@ def _load_agent_from_tools(
|
|
|
35
35
|
def load_agent_from_config(
|
|
36
36
|
config: dict,
|
|
37
37
|
llm: Optional[BaseLanguageModel] = None,
|
|
38
|
-
tools: Optional[
|
|
38
|
+
tools: Optional[list[Tool]] = None,
|
|
39
39
|
**kwargs: Any,
|
|
40
40
|
) -> Union[BaseSingleActionAgent, BaseMultiActionAgent]:
|
|
41
41
|
"""Load agent from Config Dict.
|
|
@@ -86,7 +86,7 @@ def load_agent_from_config(
|
|
|
86
86
|
del config["output_parser"]
|
|
87
87
|
|
|
88
88
|
combined_config = {**config, **kwargs}
|
|
89
|
-
return agent_cls(**combined_config)
|
|
89
|
+
return agent_cls(**combined_config)
|
|
90
90
|
|
|
91
91
|
|
|
92
92
|
@deprecated("0.1.0", removal="1.0")
|
|
@@ -130,7 +130,7 @@ def _load_agent_from_file(
|
|
|
130
130
|
with open(file_path) as f:
|
|
131
131
|
config = json.load(f)
|
|
132
132
|
elif file_path.suffix[1:] == "yaml":
|
|
133
|
-
with open(file_path
|
|
133
|
+
with open(file_path) as f:
|
|
134
134
|
config = yaml.safe_load(f)
|
|
135
135
|
else:
|
|
136
136
|
raise ValueError(f"Unsupported file type, must be one of {valid_suffixes}.")
|
langchain/agents/mrkl/base.py
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
-
from
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from typing import Any, Callable, NamedTuple, Optional
|
|
6
7
|
|
|
7
8
|
from langchain_core._api import deprecated
|
|
8
9
|
from langchain_core.callbacks import BaseCallbackManager
|
|
@@ -83,7 +84,7 @@ class ZeroShotAgent(Agent):
|
|
|
83
84
|
prefix: str = PREFIX,
|
|
84
85
|
suffix: str = SUFFIX,
|
|
85
86
|
format_instructions: str = FORMAT_INSTRUCTIONS,
|
|
86
|
-
input_variables: Optional[
|
|
87
|
+
input_variables: Optional[list[str]] = None,
|
|
87
88
|
) -> PromptTemplate:
|
|
88
89
|
"""Create prompt in the style of the zero shot agent.
|
|
89
90
|
|
|
@@ -118,7 +119,7 @@ class ZeroShotAgent(Agent):
|
|
|
118
119
|
prefix: str = PREFIX,
|
|
119
120
|
suffix: str = SUFFIX,
|
|
120
121
|
format_instructions: str = FORMAT_INSTRUCTIONS,
|
|
121
|
-
input_variables: Optional[
|
|
122
|
+
input_variables: Optional[list[str]] = None,
|
|
122
123
|
**kwargs: Any,
|
|
123
124
|
) -> Agent:
|
|
124
125
|
"""Construct an agent from an LLM and tools.
|
|
@@ -143,7 +144,7 @@ class ZeroShotAgent(Agent):
|
|
|
143
144
|
format_instructions=format_instructions,
|
|
144
145
|
input_variables=input_variables,
|
|
145
146
|
)
|
|
146
|
-
llm_chain = LLMChain(
|
|
147
|
+
llm_chain = LLMChain(
|
|
147
148
|
llm=llm,
|
|
148
149
|
prompt=prompt,
|
|
149
150
|
callback_manager=callback_manager,
|
|
@@ -183,7 +184,7 @@ class MRKLChain(AgentExecutor):
|
|
|
183
184
|
|
|
184
185
|
@classmethod
|
|
185
186
|
def from_chains(
|
|
186
|
-
cls, llm: BaseLanguageModel, chains:
|
|
187
|
+
cls, llm: BaseLanguageModel, chains: list[ChainConfig], **kwargs: Any
|
|
187
188
|
) -> AgentExecutor:
|
|
188
189
|
"""User-friendly way to initialize the MRKL chain.
|
|
189
190
|
|
|
@@ -2,18 +2,14 @@ from __future__ import annotations
|
|
|
2
2
|
|
|
3
3
|
import asyncio
|
|
4
4
|
import json
|
|
5
|
+
from collections.abc import Sequence
|
|
5
6
|
from json import JSONDecodeError
|
|
6
7
|
from time import sleep
|
|
7
8
|
from typing import (
|
|
8
9
|
TYPE_CHECKING,
|
|
9
10
|
Any,
|
|
10
11
|
Callable,
|
|
11
|
-
Dict,
|
|
12
|
-
List,
|
|
13
12
|
Optional,
|
|
14
|
-
Sequence,
|
|
15
|
-
Tuple,
|
|
16
|
-
Type,
|
|
17
13
|
Union,
|
|
18
14
|
)
|
|
19
15
|
|
|
@@ -111,7 +107,7 @@ def _get_openai_async_client() -> openai.AsyncOpenAI:
|
|
|
111
107
|
|
|
112
108
|
|
|
113
109
|
def _is_assistants_builtin_tool(
|
|
114
|
-
tool: Union[
|
|
110
|
+
tool: Union[dict[str, Any], type[BaseModel], Callable, BaseTool],
|
|
115
111
|
) -> bool:
|
|
116
112
|
"""Determine if tool corresponds to OpenAI Assistants built-in."""
|
|
117
113
|
assistants_builtin_tools = ("code_interpreter", "file_search")
|
|
@@ -123,28 +119,28 @@ def _is_assistants_builtin_tool(
|
|
|
123
119
|
|
|
124
120
|
|
|
125
121
|
def _get_assistants_tool(
|
|
126
|
-
tool: Union[
|
|
127
|
-
) ->
|
|
122
|
+
tool: Union[dict[str, Any], type[BaseModel], Callable, BaseTool],
|
|
123
|
+
) -> dict[str, Any]:
|
|
128
124
|
"""Convert a raw function/class to an OpenAI tool.
|
|
129
125
|
|
|
130
126
|
Note that OpenAI assistants supports several built-in tools,
|
|
131
127
|
such as "code_interpreter" and "file_search".
|
|
132
128
|
"""
|
|
133
129
|
if _is_assistants_builtin_tool(tool):
|
|
134
|
-
return tool # type: ignore
|
|
130
|
+
return tool # type: ignore[return-value]
|
|
135
131
|
else:
|
|
136
132
|
return convert_to_openai_tool(tool)
|
|
137
133
|
|
|
138
134
|
|
|
139
135
|
OutputType = Union[
|
|
140
|
-
|
|
136
|
+
list[OpenAIAssistantAction],
|
|
141
137
|
OpenAIAssistantFinish,
|
|
142
|
-
|
|
143
|
-
|
|
138
|
+
list["ThreadMessage"],
|
|
139
|
+
list["RequiredActionFunctionToolCall"],
|
|
144
140
|
]
|
|
145
141
|
|
|
146
142
|
|
|
147
|
-
class OpenAIAssistantRunnable(RunnableSerializable[
|
|
143
|
+
class OpenAIAssistantRunnable(RunnableSerializable[dict, OutputType]):
|
|
148
144
|
"""Run an OpenAI Assistant.
|
|
149
145
|
|
|
150
146
|
Example using OpenAI tools:
|
|
@@ -271,7 +267,7 @@ class OpenAIAssistantRunnable(RunnableSerializable[Dict, OutputType]):
|
|
|
271
267
|
assistant = client.beta.assistants.create(
|
|
272
268
|
name=name,
|
|
273
269
|
instructions=instructions,
|
|
274
|
-
tools=[_get_assistants_tool(tool) for tool in tools], # type: ignore
|
|
270
|
+
tools=[_get_assistants_tool(tool) for tool in tools], # type: ignore[misc]
|
|
275
271
|
model=model,
|
|
276
272
|
)
|
|
277
273
|
return cls(assistant_id=assistant.id, client=client, **kwargs)
|
|
@@ -398,7 +394,7 @@ class OpenAIAssistantRunnable(RunnableSerializable[Dict, OutputType]):
|
|
|
398
394
|
assistant = await async_client.beta.assistants.create(
|
|
399
395
|
name=name,
|
|
400
396
|
instructions=instructions,
|
|
401
|
-
tools=openai_tools, # type: ignore
|
|
397
|
+
tools=openai_tools, # type: ignore[arg-type]
|
|
402
398
|
model=model,
|
|
403
399
|
)
|
|
404
400
|
return cls(assistant_id=assistant.id, async_client=async_client, **kwargs)
|
|
@@ -498,7 +494,7 @@ class OpenAIAssistantRunnable(RunnableSerializable[Dict, OutputType]):
|
|
|
498
494
|
return response
|
|
499
495
|
|
|
500
496
|
def _parse_intermediate_steps(
|
|
501
|
-
self, intermediate_steps:
|
|
497
|
+
self, intermediate_steps: list[tuple[OpenAIAssistantAction, str]]
|
|
502
498
|
) -> dict:
|
|
503
499
|
last_action, last_output = intermediate_steps[-1]
|
|
504
500
|
run = self._wait_for_run(last_action.run_id, last_action.thread_id)
|
|
@@ -652,7 +648,7 @@ class OpenAIAssistantRunnable(RunnableSerializable[Dict, OutputType]):
|
|
|
652
648
|
return run
|
|
653
649
|
|
|
654
650
|
async def _aparse_intermediate_steps(
|
|
655
|
-
self, intermediate_steps:
|
|
651
|
+
self, intermediate_steps: list[tuple[OpenAIAssistantAction, str]]
|
|
656
652
|
) -> dict:
|
|
657
653
|
last_action, last_output = intermediate_steps[-1]
|
|
658
654
|
run = self._wait_for_run(last_action.run_id, last_action.thread_id)
|