langchain 0.2.6__py3-none-any.whl → 0.2.8__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/__init__.py +1 -0
- langchain/agents/__init__.py +5 -4
- langchain/agents/agent.py +272 -50
- langchain/agents/agent_iterator.py +20 -0
- langchain/agents/agent_toolkits/__init__.py +1 -0
- langchain/agents/agent_toolkits/file_management/__init__.py +1 -0
- langchain/agents/agent_toolkits/playwright/__init__.py +1 -0
- langchain/agents/agent_toolkits/vectorstore/base.py +1 -0
- langchain/agents/agent_toolkits/vectorstore/toolkit.py +1 -0
- langchain/agents/agent_types.py +1 -0
- langchain/agents/chat/base.py +37 -1
- langchain/agents/chat/output_parser.py +14 -0
- langchain/agents/conversational/base.py +38 -6
- langchain/agents/conversational/output_parser.py +10 -0
- langchain/agents/conversational_chat/base.py +42 -3
- langchain/agents/format_scratchpad/__init__.py +1 -0
- langchain/agents/format_scratchpad/log.py +12 -1
- langchain/agents/format_scratchpad/log_to_messages.py +10 -1
- langchain/agents/format_scratchpad/openai_functions.py +10 -5
- langchain/agents/format_scratchpad/tools.py +11 -7
- langchain/agents/initialize.py +15 -7
- langchain/agents/json_chat/base.py +6 -0
- langchain/agents/loading.py +7 -0
- langchain/agents/mrkl/base.py +39 -10
- langchain/agents/mrkl/output_parser.py +12 -0
- langchain/agents/openai_assistant/base.py +37 -14
- langchain/agents/openai_functions_agent/agent_token_buffer_memory.py +32 -4
- langchain/agents/openai_functions_agent/base.py +61 -10
- langchain/agents/openai_functions_multi_agent/base.py +22 -7
- langchain/agents/openai_tools/base.py +3 -0
- langchain/agents/output_parsers/__init__.py +1 -0
- langchain/agents/react/base.py +1 -0
- langchain/agents/self_ask_with_search/base.py +1 -0
- langchain/agents/structured_chat/output_parser.py +3 -3
- langchain/agents/tools.py +3 -0
- langchain/agents/utils.py +9 -1
- langchain/base_language.py +1 -0
- langchain/callbacks/__init__.py +1 -0
- langchain/callbacks/base.py +1 -0
- langchain/callbacks/streaming_stdout.py +1 -0
- langchain/callbacks/streaming_stdout_final_only.py +1 -0
- langchain/callbacks/tracers/evaluation.py +1 -0
- langchain/chains/api/base.py +5 -2
- langchain/chains/base.py +1 -1
- langchain/chains/combine_documents/base.py +59 -0
- langchain/chains/combine_documents/map_reduce.py +4 -2
- langchain/chains/combine_documents/map_rerank.py +5 -3
- langchain/chains/combine_documents/refine.py +4 -2
- langchain/chains/combine_documents/stuff.py +9 -4
- langchain/chains/constitutional_ai/base.py +1 -0
- langchain/chains/constitutional_ai/models.py +1 -0
- langchain/chains/constitutional_ai/principles.py +1 -0
- langchain/chains/conversation/base.py +81 -1
- langchain/chains/conversational_retrieval/base.py +2 -1
- langchain/chains/elasticsearch_database/base.py +2 -1
- langchain/chains/hyde/base.py +1 -0
- langchain/chains/llm.py +1 -0
- langchain/chains/llm_checker/base.py +4 -3
- langchain/chains/llm_math/base.py +1 -0
- langchain/chains/loading.py +2 -1
- langchain/chains/mapreduce.py +1 -0
- langchain/chains/moderation.py +1 -1
- langchain/chains/natbot/base.py +1 -0
- langchain/chains/openai_functions/base.py +1 -0
- langchain/chains/qa_generation/base.py +47 -1
- langchain/chains/qa_with_sources/__init__.py +1 -0
- langchain/chains/qa_with_sources/loading.py +1 -0
- langchain/chains/qa_with_sources/vector_db.py +1 -1
- langchain/chains/query_constructor/base.py +1 -0
- langchain/chains/query_constructor/ir.py +1 -0
- langchain/chains/question_answering/chain.py +1 -0
- langchain/chains/retrieval_qa/base.py +3 -2
- langchain/chains/router/base.py +1 -0
- langchain/chains/router/llm_router.py +2 -1
- langchain/chains/router/multi_prompt.py +1 -0
- langchain/chains/router/multi_retrieval_qa.py +1 -0
- langchain/chains/sequential.py +2 -1
- langchain/chains/structured_output/base.py +6 -6
- langchain/chains/summarize/chain.py +1 -0
- langchain/chains/transform.py +4 -3
- langchain/chat_models/__init__.py +1 -0
- langchain/chat_models/base.py +607 -9
- langchain/docstore/__init__.py +1 -0
- langchain/document_loaders/__init__.py +1 -0
- langchain/document_transformers/__init__.py +1 -0
- langchain/embeddings/__init__.py +0 -1
- langchain/evaluation/__init__.py +2 -1
- langchain/evaluation/agents/__init__.py +1 -0
- langchain/evaluation/agents/trajectory_eval_prompt.py +1 -0
- langchain/evaluation/comparison/__init__.py +1 -0
- langchain/evaluation/comparison/eval_chain.py +1 -0
- langchain/evaluation/comparison/prompt.py +1 -0
- langchain/evaluation/embedding_distance/__init__.py +1 -0
- langchain/evaluation/embedding_distance/base.py +1 -0
- langchain/evaluation/loading.py +1 -0
- langchain/evaluation/parsing/base.py +1 -0
- langchain/evaluation/qa/__init__.py +1 -0
- langchain/evaluation/qa/eval_chain.py +1 -0
- langchain/evaluation/qa/generate_chain.py +1 -0
- langchain/evaluation/schema.py +1 -0
- langchain/evaluation/scoring/__init__.py +1 -0
- langchain/evaluation/scoring/eval_chain.py +1 -0
- langchain/evaluation/scoring/prompt.py +1 -0
- langchain/evaluation/string_distance/__init__.py +1 -0
- langchain/example_generator.py +1 -0
- langchain/formatting.py +1 -0
- langchain/globals/__init__.py +1 -0
- langchain/graphs/__init__.py +1 -0
- langchain/indexes/__init__.py +1 -0
- langchain/indexes/_sql_record_manager.py +1 -2
- langchain/indexes/graph.py +1 -0
- langchain/indexes/prompts/__init__.py +1 -0
- langchain/input.py +1 -0
- langchain/llms/__init__.py +1 -0
- langchain/load/__init__.py +1 -0
- langchain/memory/__init__.py +5 -0
- langchain/memory/vectorstore_token_buffer_memory.py +184 -0
- langchain/output_parsers/__init__.py +1 -0
- langchain/prompts/__init__.py +1 -0
- langchain/prompts/example_selector/__init__.py +1 -0
- langchain/python.py +1 -0
- langchain/requests.py +1 -0
- langchain/retrievers/__init__.py +1 -0
- langchain/retrievers/document_compressors/chain_extract.py +1 -0
- langchain/retrievers/document_compressors/chain_filter.py +1 -0
- langchain/retrievers/ensemble.py +1 -0
- langchain/retrievers/self_query/base.py +7 -7
- langchain/schema/__init__.py +1 -0
- langchain/schema/runnable/__init__.py +1 -0
- langchain/serpapi.py +1 -0
- langchain/smith/__init__.py +6 -5
- langchain/smith/evaluation/__init__.py +0 -1
- langchain/smith/evaluation/string_run_evaluator.py +1 -0
- langchain/sql_database.py +1 -0
- langchain/storage/__init__.py +1 -0
- langchain/storage/_lc_store.py +1 -0
- langchain/storage/in_memory.py +1 -0
- langchain/text_splitter.py +1 -0
- langchain/tools/__init__.py +1 -0
- langchain/tools/amadeus/__init__.py +1 -0
- langchain/tools/azure_cognitive_services/__init__.py +1 -0
- langchain/tools/bing_search/__init__.py +1 -0
- langchain/tools/dataforseo_api_search/__init__.py +1 -0
- langchain/tools/ddg_search/__init__.py +1 -0
- langchain/tools/edenai/__init__.py +1 -0
- langchain/tools/eleven_labs/__init__.py +1 -0
- langchain/tools/file_management/__init__.py +1 -0
- langchain/tools/github/__init__.py +1 -1
- langchain/tools/gitlab/__init__.py +1 -1
- langchain/tools/gmail/__init__.py +1 -0
- langchain/tools/golden_query/__init__.py +1 -0
- langchain/tools/google_cloud/__init__.py +1 -0
- langchain/tools/google_finance/__init__.py +1 -0
- langchain/tools/google_jobs/__init__.py +1 -0
- langchain/tools/google_lens/__init__.py +1 -0
- langchain/tools/google_places/__init__.py +1 -0
- langchain/tools/google_scholar/__init__.py +1 -0
- langchain/tools/google_search/__init__.py +1 -0
- langchain/tools/google_trends/__init__.py +1 -0
- langchain/tools/human/__init__.py +1 -0
- langchain/tools/memorize/__init__.py +1 -0
- langchain/tools/metaphor_search/__init__.py +1 -0
- langchain/tools/multion/__init__.py +1 -0
- langchain/tools/office365/__init__.py +1 -0
- langchain/tools/openapi/utils/openapi_utils.py +1 -0
- langchain/tools/openweathermap/__init__.py +1 -0
- langchain/tools/playwright/__init__.py +1 -0
- langchain/tools/shell/__init__.py +1 -0
- langchain/tools/slack/__init__.py +1 -0
- langchain/tools/sql_database/prompt.py +1 -0
- langchain/tools/steamship_image_generation/__init__.py +1 -0
- langchain/tools/tavily_search/__init__.py +1 -0
- langchain/tools/wolfram_alpha/__init__.py +1 -0
- langchain/tools/zapier/__init__.py +1 -0
- langchain/utilities/__init__.py +1 -0
- langchain/utilities/python.py +1 -0
- langchain/vectorstores/__init__.py +1 -0
- {langchain-0.2.6.dist-info → langchain-0.2.8.dist-info}/METADATA +2 -3
- {langchain-0.2.6.dist-info → langchain-0.2.8.dist-info}/RECORD +182 -181
- {langchain-0.2.6.dist-info → langchain-0.2.8.dist-info}/LICENSE +0 -0
- {langchain-0.2.6.dist-info → langchain-0.2.8.dist-info}/WHEEL +0 -0
- {langchain-0.2.6.dist-info → langchain-0.2.8.dist-info}/entry_points.txt +0 -0
langchain/__init__.py
CHANGED
langchain/agents/__init__.py
CHANGED
|
@@ -15,19 +15,20 @@ Agents select and use **Tools** and **Toolkits** for actions.
|
|
|
15
15
|
OpenAIFunctionsAgent
|
|
16
16
|
XMLAgent
|
|
17
17
|
Agent --> <name>Agent # Examples: ZeroShotAgent, ChatAgent
|
|
18
|
-
|
|
18
|
+
|
|
19
19
|
|
|
20
20
|
BaseMultiActionAgent --> OpenAIMultiFunctionsAgent
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
|
|
22
|
+
|
|
23
23
|
**Main helpers:**
|
|
24
24
|
|
|
25
25
|
.. code-block::
|
|
26
26
|
|
|
27
27
|
AgentType, AgentExecutor, AgentOutputParser, AgentExecutorIterator,
|
|
28
28
|
AgentAction, AgentFinish
|
|
29
|
-
|
|
29
|
+
|
|
30
30
|
""" # noqa: E501
|
|
31
|
+
|
|
31
32
|
from pathlib import Path
|
|
32
33
|
from typing import TYPE_CHECKING, Any
|
|
33
34
|
|
langchain/agents/agent.py
CHANGED
|
@@ -77,7 +77,7 @@ class BaseSingleActionAgent(BaseModel):
|
|
|
77
77
|
|
|
78
78
|
Args:
|
|
79
79
|
intermediate_steps: Steps the LLM has taken to date,
|
|
80
|
-
along with observations
|
|
80
|
+
along with observations.
|
|
81
81
|
callbacks: Callbacks to run.
|
|
82
82
|
**kwargs: User inputs.
|
|
83
83
|
|
|
@@ -92,11 +92,11 @@ class BaseSingleActionAgent(BaseModel):
|
|
|
92
92
|
callbacks: Callbacks = None,
|
|
93
93
|
**kwargs: Any,
|
|
94
94
|
) -> Union[AgentAction, AgentFinish]:
|
|
95
|
-
"""
|
|
95
|
+
"""Async given input, decided what to do.
|
|
96
96
|
|
|
97
97
|
Args:
|
|
98
98
|
intermediate_steps: Steps the LLM has taken to date,
|
|
99
|
-
along with observations
|
|
99
|
+
along with observations.
|
|
100
100
|
callbacks: Callbacks to run.
|
|
101
101
|
**kwargs: User inputs.
|
|
102
102
|
|
|
@@ -118,7 +118,20 @@ class BaseSingleActionAgent(BaseModel):
|
|
|
118
118
|
intermediate_steps: List[Tuple[AgentAction, str]],
|
|
119
119
|
**kwargs: Any,
|
|
120
120
|
) -> AgentFinish:
|
|
121
|
-
"""Return response when agent has been stopped due to max iterations.
|
|
121
|
+
"""Return response when agent has been stopped due to max iterations.
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
early_stopping_method: Method to use for early stopping.
|
|
125
|
+
intermediate_steps: Steps the LLM has taken to date,
|
|
126
|
+
along with observations.
|
|
127
|
+
**kwargs: User inputs.
|
|
128
|
+
|
|
129
|
+
Returns:
|
|
130
|
+
AgentFinish: Agent finish object.
|
|
131
|
+
|
|
132
|
+
Raises:
|
|
133
|
+
ValueError: If `early_stopping_method` is not supported.
|
|
134
|
+
"""
|
|
122
135
|
if early_stopping_method == "force":
|
|
123
136
|
# `force` just returns a constant string
|
|
124
137
|
return AgentFinish(
|
|
@@ -137,15 +150,30 @@ class BaseSingleActionAgent(BaseModel):
|
|
|
137
150
|
callback_manager: Optional[BaseCallbackManager] = None,
|
|
138
151
|
**kwargs: Any,
|
|
139
152
|
) -> BaseSingleActionAgent:
|
|
153
|
+
"""Construct an agent from an LLM and tools.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
llm: Language model to use.
|
|
157
|
+
tools: Tools to use.
|
|
158
|
+
callback_manager: Callback manager to use.
|
|
159
|
+
**kwargs: Additional arguments.
|
|
160
|
+
|
|
161
|
+
Returns:
|
|
162
|
+
BaseSingleActionAgent: Agent object.
|
|
163
|
+
"""
|
|
140
164
|
raise NotImplementedError
|
|
141
165
|
|
|
142
166
|
@property
|
|
143
167
|
def _agent_type(self) -> str:
|
|
144
|
-
"""Return Identifier of agent type."""
|
|
168
|
+
"""Return Identifier of an agent type."""
|
|
145
169
|
raise NotImplementedError
|
|
146
170
|
|
|
147
171
|
def dict(self, **kwargs: Any) -> Dict:
|
|
148
|
-
"""Return dictionary representation of agent.
|
|
172
|
+
"""Return dictionary representation of agent.
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
Dict: Dictionary representation of agent.
|
|
176
|
+
"""
|
|
149
177
|
_dict = super().dict()
|
|
150
178
|
try:
|
|
151
179
|
_type = self._agent_type
|
|
@@ -193,6 +221,7 @@ class BaseSingleActionAgent(BaseModel):
|
|
|
193
221
|
raise ValueError(f"{save_path} must be json or yaml")
|
|
194
222
|
|
|
195
223
|
def tool_run_logging_kwargs(self) -> Dict:
|
|
224
|
+
"""Return logging kwargs for tool run."""
|
|
196
225
|
return {}
|
|
197
226
|
|
|
198
227
|
|
|
@@ -205,6 +234,11 @@ class BaseMultiActionAgent(BaseModel):
|
|
|
205
234
|
return ["output"]
|
|
206
235
|
|
|
207
236
|
def get_allowed_tools(self) -> Optional[List[str]]:
|
|
237
|
+
"""Get allowed tools.
|
|
238
|
+
|
|
239
|
+
Returns:
|
|
240
|
+
Optional[List[str]]: Allowed tools.
|
|
241
|
+
"""
|
|
208
242
|
return None
|
|
209
243
|
|
|
210
244
|
@abstractmethod
|
|
@@ -233,7 +267,7 @@ class BaseMultiActionAgent(BaseModel):
|
|
|
233
267
|
callbacks: Callbacks = None,
|
|
234
268
|
**kwargs: Any,
|
|
235
269
|
) -> Union[List[AgentAction], AgentFinish]:
|
|
236
|
-
"""
|
|
270
|
+
"""Async given input, decided what to do.
|
|
237
271
|
|
|
238
272
|
Args:
|
|
239
273
|
intermediate_steps: Steps the LLM has taken to date,
|
|
@@ -259,7 +293,20 @@ class BaseMultiActionAgent(BaseModel):
|
|
|
259
293
|
intermediate_steps: List[Tuple[AgentAction, str]],
|
|
260
294
|
**kwargs: Any,
|
|
261
295
|
) -> AgentFinish:
|
|
262
|
-
"""Return response when agent has been stopped due to max iterations.
|
|
296
|
+
"""Return response when agent has been stopped due to max iterations.
|
|
297
|
+
|
|
298
|
+
Args:
|
|
299
|
+
early_stopping_method: Method to use for early stopping.
|
|
300
|
+
intermediate_steps: Steps the LLM has taken to date,
|
|
301
|
+
along with observations.
|
|
302
|
+
**kwargs: User inputs.
|
|
303
|
+
|
|
304
|
+
Returns:
|
|
305
|
+
AgentFinish: Agent finish object.
|
|
306
|
+
|
|
307
|
+
Raises:
|
|
308
|
+
ValueError: If `early_stopping_method` is not supported.
|
|
309
|
+
"""
|
|
263
310
|
if early_stopping_method == "force":
|
|
264
311
|
# `force` just returns a constant string
|
|
265
312
|
return AgentFinish({"output": "Agent stopped due to max iterations."}, "")
|
|
@@ -270,7 +317,7 @@ class BaseMultiActionAgent(BaseModel):
|
|
|
270
317
|
|
|
271
318
|
@property
|
|
272
319
|
def _agent_type(self) -> str:
|
|
273
|
-
"""Return Identifier of agent type."""
|
|
320
|
+
"""Return Identifier of an agent type."""
|
|
274
321
|
raise NotImplementedError
|
|
275
322
|
|
|
276
323
|
def dict(self, **kwargs: Any) -> Dict:
|
|
@@ -288,6 +335,10 @@ class BaseMultiActionAgent(BaseModel):
|
|
|
288
335
|
Args:
|
|
289
336
|
file_path: Path to file to save the agent to.
|
|
290
337
|
|
|
338
|
+
Raises:
|
|
339
|
+
NotImplementedError: If agent does not support saving.
|
|
340
|
+
ValueError: If file_path is not json or yaml.
|
|
341
|
+
|
|
291
342
|
Example:
|
|
292
343
|
.. code-block:: python
|
|
293
344
|
|
|
@@ -318,6 +369,8 @@ class BaseMultiActionAgent(BaseModel):
|
|
|
318
369
|
raise ValueError(f"{save_path} must be json or yaml")
|
|
319
370
|
|
|
320
371
|
def tool_run_logging_kwargs(self) -> Dict:
|
|
372
|
+
"""Return logging kwargs for tool run."""
|
|
373
|
+
|
|
321
374
|
return {}
|
|
322
375
|
|
|
323
376
|
|
|
@@ -332,15 +385,26 @@ class AgentOutputParser(BaseOutputParser[Union[AgentAction, AgentFinish]]):
|
|
|
332
385
|
class MultiActionAgentOutputParser(
|
|
333
386
|
BaseOutputParser[Union[List[AgentAction], AgentFinish]]
|
|
334
387
|
):
|
|
335
|
-
"""Base class for parsing agent output into agent actions/finish.
|
|
388
|
+
"""Base class for parsing agent output into agent actions/finish.
|
|
389
|
+
|
|
390
|
+
This is used for agents that can return multiple actions.
|
|
391
|
+
"""
|
|
336
392
|
|
|
337
393
|
@abstractmethod
|
|
338
394
|
def parse(self, text: str) -> Union[List[AgentAction], AgentFinish]:
|
|
339
|
-
"""Parse text into agent actions/finish.
|
|
395
|
+
"""Parse text into agent actions/finish.
|
|
396
|
+
|
|
397
|
+
Args:
|
|
398
|
+
text: Text to parse.
|
|
399
|
+
|
|
400
|
+
Returns:
|
|
401
|
+
Union[List[AgentAction], AgentFinish]:
|
|
402
|
+
List of agent actions or agent finish.
|
|
403
|
+
"""
|
|
340
404
|
|
|
341
405
|
|
|
342
406
|
class RunnableAgent(BaseSingleActionAgent):
|
|
343
|
-
"""Agent powered by
|
|
407
|
+
"""Agent powered by Runnables."""
|
|
344
408
|
|
|
345
409
|
runnable: Runnable[dict, Union[AgentAction, AgentFinish]]
|
|
346
410
|
"""Runnable to call to get agent action."""
|
|
@@ -367,6 +431,7 @@ class RunnableAgent(BaseSingleActionAgent):
|
|
|
367
431
|
|
|
368
432
|
@property
|
|
369
433
|
def input_keys(self) -> List[str]:
|
|
434
|
+
"""Return the input keys."""
|
|
370
435
|
return self.input_keys_arg
|
|
371
436
|
|
|
372
437
|
def plan(
|
|
@@ -414,13 +479,13 @@ class RunnableAgent(BaseSingleActionAgent):
|
|
|
414
479
|
AgentAction,
|
|
415
480
|
AgentFinish,
|
|
416
481
|
]:
|
|
417
|
-
"""
|
|
482
|
+
"""Async based on past history and current inputs, decide what to do.
|
|
418
483
|
|
|
419
484
|
Args:
|
|
420
485
|
intermediate_steps: Steps the LLM has taken to date,
|
|
421
|
-
along with observations
|
|
486
|
+
along with observations.
|
|
422
487
|
callbacks: Callbacks to run.
|
|
423
|
-
**kwargs: User inputs
|
|
488
|
+
**kwargs: User inputs.
|
|
424
489
|
|
|
425
490
|
Returns:
|
|
426
491
|
Action specifying what tool to use.
|
|
@@ -449,7 +514,7 @@ class RunnableAgent(BaseSingleActionAgent):
|
|
|
449
514
|
|
|
450
515
|
|
|
451
516
|
class RunnableMultiActionAgent(BaseMultiActionAgent):
|
|
452
|
-
"""Agent powered by
|
|
517
|
+
"""Agent powered by Runnables."""
|
|
453
518
|
|
|
454
519
|
runnable: Runnable[dict, Union[List[AgentAction], AgentFinish]]
|
|
455
520
|
"""Runnable to call to get agent actions."""
|
|
@@ -531,11 +596,11 @@ class RunnableMultiActionAgent(BaseMultiActionAgent):
|
|
|
531
596
|
List[AgentAction],
|
|
532
597
|
AgentFinish,
|
|
533
598
|
]:
|
|
534
|
-
"""
|
|
599
|
+
"""Async based on past history and current inputs, decide what to do.
|
|
535
600
|
|
|
536
601
|
Args:
|
|
537
602
|
intermediate_steps: Steps the LLM has taken to date,
|
|
538
|
-
along with observations
|
|
603
|
+
along with observations.
|
|
539
604
|
callbacks: Callbacks to run.
|
|
540
605
|
**kwargs: User inputs.
|
|
541
606
|
|
|
@@ -630,11 +695,11 @@ class LLMSingleActionAgent(BaseSingleActionAgent):
|
|
|
630
695
|
callbacks: Callbacks = None,
|
|
631
696
|
**kwargs: Any,
|
|
632
697
|
) -> Union[AgentAction, AgentFinish]:
|
|
633
|
-
"""
|
|
698
|
+
"""Async given input, decided what to do.
|
|
634
699
|
|
|
635
700
|
Args:
|
|
636
701
|
intermediate_steps: Steps the LLM has taken to date,
|
|
637
|
-
along with observations
|
|
702
|
+
along with observations.
|
|
638
703
|
callbacks: Callbacks to run.
|
|
639
704
|
**kwargs: User inputs.
|
|
640
705
|
|
|
@@ -650,6 +715,7 @@ class LLMSingleActionAgent(BaseSingleActionAgent):
|
|
|
650
715
|
return self.output_parser.parse(output)
|
|
651
716
|
|
|
652
717
|
def tool_run_logging_kwargs(self) -> Dict:
|
|
718
|
+
"""Return logging kwargs for tool run."""
|
|
653
719
|
return {
|
|
654
720
|
"llm_prefix": "",
|
|
655
721
|
"observation_prefix": "" if len(self.stop) == 0 else self.stop[0],
|
|
@@ -667,14 +733,17 @@ class LLMSingleActionAgent(BaseSingleActionAgent):
|
|
|
667
733
|
class Agent(BaseSingleActionAgent):
|
|
668
734
|
"""Agent that calls the language model and deciding the action.
|
|
669
735
|
|
|
670
|
-
This is driven by
|
|
736
|
+
This is driven by a LLMChain. The prompt in the LLMChain MUST include
|
|
671
737
|
a variable called "agent_scratchpad" where the agent can put its
|
|
672
738
|
intermediary work.
|
|
673
739
|
"""
|
|
674
740
|
|
|
675
741
|
llm_chain: LLMChain
|
|
742
|
+
"""LLMChain to use for agent."""
|
|
676
743
|
output_parser: AgentOutputParser
|
|
744
|
+
"""Output parser to use for agent."""
|
|
677
745
|
allowed_tools: Optional[List[str]] = None
|
|
746
|
+
"""Allowed tools for the agent. If None, all tools are allowed."""
|
|
678
747
|
|
|
679
748
|
def dict(self, **kwargs: Any) -> Dict:
|
|
680
749
|
"""Return dictionary representation of agent."""
|
|
@@ -683,14 +752,23 @@ class Agent(BaseSingleActionAgent):
|
|
|
683
752
|
return _dict
|
|
684
753
|
|
|
685
754
|
def get_allowed_tools(self) -> Optional[List[str]]:
|
|
755
|
+
"""Get allowed tools."""
|
|
686
756
|
return self.allowed_tools
|
|
687
757
|
|
|
688
758
|
@property
|
|
689
759
|
def return_values(self) -> List[str]:
|
|
760
|
+
"""Return values of the agent."""
|
|
690
761
|
return ["output"]
|
|
691
762
|
|
|
692
763
|
def _fix_text(self, text: str) -> str:
|
|
693
|
-
"""Fix the text.
|
|
764
|
+
"""Fix the text.
|
|
765
|
+
|
|
766
|
+
Args:
|
|
767
|
+
text: Text to fix.
|
|
768
|
+
|
|
769
|
+
Returns:
|
|
770
|
+
str: Fixed text.
|
|
771
|
+
"""
|
|
694
772
|
raise ValueError("fix_text not implemented for this agent.")
|
|
695
773
|
|
|
696
774
|
@property
|
|
@@ -720,7 +798,7 @@ class Agent(BaseSingleActionAgent):
|
|
|
720
798
|
|
|
721
799
|
Args:
|
|
722
800
|
intermediate_steps: Steps the LLM has taken to date,
|
|
723
|
-
along with observations
|
|
801
|
+
along with observations.
|
|
724
802
|
callbacks: Callbacks to run.
|
|
725
803
|
**kwargs: User inputs.
|
|
726
804
|
|
|
@@ -737,11 +815,11 @@ class Agent(BaseSingleActionAgent):
|
|
|
737
815
|
callbacks: Callbacks = None,
|
|
738
816
|
**kwargs: Any,
|
|
739
817
|
) -> Union[AgentAction, AgentFinish]:
|
|
740
|
-
"""
|
|
818
|
+
"""Async given input, decided what to do.
|
|
741
819
|
|
|
742
820
|
Args:
|
|
743
821
|
intermediate_steps: Steps the LLM has taken to date,
|
|
744
|
-
along with observations
|
|
822
|
+
along with observations.
|
|
745
823
|
callbacks: Callbacks to run.
|
|
746
824
|
**kwargs: User inputs.
|
|
747
825
|
|
|
@@ -756,7 +834,16 @@ class Agent(BaseSingleActionAgent):
|
|
|
756
834
|
def get_full_inputs(
|
|
757
835
|
self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any
|
|
758
836
|
) -> Dict[str, Any]:
|
|
759
|
-
"""Create the full inputs for the LLMChain from intermediate steps.
|
|
837
|
+
"""Create the full inputs for the LLMChain from intermediate steps.
|
|
838
|
+
|
|
839
|
+
Args:
|
|
840
|
+
intermediate_steps: Steps the LLM has taken to date,
|
|
841
|
+
along with observations.
|
|
842
|
+
**kwargs: User inputs.
|
|
843
|
+
|
|
844
|
+
Returns:
|
|
845
|
+
Dict[str, Any]: Full inputs for the LLMChain.
|
|
846
|
+
"""
|
|
760
847
|
thoughts = self._construct_scratchpad(intermediate_steps)
|
|
761
848
|
new_inputs = {"agent_scratchpad": thoughts, "stop": self._stop}
|
|
762
849
|
full_inputs = {**kwargs, **new_inputs}
|
|
@@ -770,9 +857,20 @@ class Agent(BaseSingleActionAgent):
|
|
|
770
857
|
"""
|
|
771
858
|
return list(set(self.llm_chain.input_keys) - {"agent_scratchpad"})
|
|
772
859
|
|
|
773
|
-
@root_validator()
|
|
860
|
+
@root_validator(pre=False, skip_on_failure=True)
|
|
774
861
|
def validate_prompt(cls, values: Dict) -> Dict:
|
|
775
|
-
"""Validate that prompt matches format.
|
|
862
|
+
"""Validate that prompt matches format.
|
|
863
|
+
|
|
864
|
+
Args:
|
|
865
|
+
values: Values to validate.
|
|
866
|
+
|
|
867
|
+
Returns:
|
|
868
|
+
Dict: Validated values.
|
|
869
|
+
|
|
870
|
+
Raises:
|
|
871
|
+
ValueError: If `agent_scratchpad` is not in prompt.input_variables
|
|
872
|
+
and prompt is not a FewShotPromptTemplate or a PromptTemplate.
|
|
873
|
+
"""
|
|
776
874
|
prompt = values["llm_chain"].prompt
|
|
777
875
|
if "agent_scratchpad" not in prompt.input_variables:
|
|
778
876
|
logger.warning(
|
|
@@ -801,11 +899,23 @@ class Agent(BaseSingleActionAgent):
|
|
|
801
899
|
@classmethod
|
|
802
900
|
@abstractmethod
|
|
803
901
|
def create_prompt(cls, tools: Sequence[BaseTool]) -> BasePromptTemplate:
|
|
804
|
-
"""Create a prompt for this class.
|
|
902
|
+
"""Create a prompt for this class.
|
|
903
|
+
|
|
904
|
+
Args:
|
|
905
|
+
tools: Tools to use.
|
|
906
|
+
|
|
907
|
+
Returns:
|
|
908
|
+
BasePromptTemplate: Prompt template.
|
|
909
|
+
"""
|
|
805
910
|
|
|
806
911
|
@classmethod
|
|
807
912
|
def _validate_tools(cls, tools: Sequence[BaseTool]) -> None:
|
|
808
|
-
"""Validate that appropriate tools are passed in.
|
|
913
|
+
"""Validate that appropriate tools are passed in.
|
|
914
|
+
|
|
915
|
+
Args:
|
|
916
|
+
tools: Tools to use.
|
|
917
|
+
"""
|
|
918
|
+
|
|
809
919
|
pass
|
|
810
920
|
|
|
811
921
|
@classmethod
|
|
@@ -822,7 +932,18 @@ class Agent(BaseSingleActionAgent):
|
|
|
822
932
|
output_parser: Optional[AgentOutputParser] = None,
|
|
823
933
|
**kwargs: Any,
|
|
824
934
|
) -> Agent:
|
|
825
|
-
"""Construct an agent from an LLM and tools.
|
|
935
|
+
"""Construct an agent from an LLM and tools.
|
|
936
|
+
|
|
937
|
+
Args:
|
|
938
|
+
llm: Language model to use.
|
|
939
|
+
tools: Tools to use.
|
|
940
|
+
callback_manager: Callback manager to use.
|
|
941
|
+
output_parser: Output parser to use.
|
|
942
|
+
**kwargs: Additional arguments.
|
|
943
|
+
|
|
944
|
+
Returns:
|
|
945
|
+
Agent: Agent object.
|
|
946
|
+
"""
|
|
826
947
|
cls._validate_tools(tools)
|
|
827
948
|
llm_chain = LLMChain(
|
|
828
949
|
llm=llm,
|
|
@@ -844,7 +965,20 @@ class Agent(BaseSingleActionAgent):
|
|
|
844
965
|
intermediate_steps: List[Tuple[AgentAction, str]],
|
|
845
966
|
**kwargs: Any,
|
|
846
967
|
) -> AgentFinish:
|
|
847
|
-
"""Return response when agent has been stopped due to max iterations.
|
|
968
|
+
"""Return response when agent has been stopped due to max iterations.
|
|
969
|
+
|
|
970
|
+
Args:
|
|
971
|
+
early_stopping_method: Method to use for early stopping.
|
|
972
|
+
intermediate_steps: Steps the LLM has taken to date,
|
|
973
|
+
along with observations.
|
|
974
|
+
**kwargs: User inputs.
|
|
975
|
+
|
|
976
|
+
Returns:
|
|
977
|
+
AgentFinish: Agent finish object.
|
|
978
|
+
|
|
979
|
+
Raises:
|
|
980
|
+
ValueError: If `early_stopping_method` is not in ['force', 'generate'].
|
|
981
|
+
"""
|
|
848
982
|
if early_stopping_method == "force":
|
|
849
983
|
# `force` just returns a constant string
|
|
850
984
|
return AgentFinish(
|
|
@@ -881,6 +1015,7 @@ class Agent(BaseSingleActionAgent):
|
|
|
881
1015
|
)
|
|
882
1016
|
|
|
883
1017
|
def tool_run_logging_kwargs(self) -> Dict:
|
|
1018
|
+
"""Return logging kwargs for tool run."""
|
|
884
1019
|
return {
|
|
885
1020
|
"llm_prefix": self.llm_prefix,
|
|
886
1021
|
"observation_prefix": self.observation_prefix,
|
|
@@ -943,9 +1078,9 @@ class AgentExecutor(Chain):
|
|
|
943
1078
|
`"generate"` calls the agent's LLM Chain one final time to generate
|
|
944
1079
|
a final answer based on the previous steps.
|
|
945
1080
|
"""
|
|
946
|
-
handle_parsing_errors: Union[
|
|
947
|
-
|
|
948
|
-
|
|
1081
|
+
handle_parsing_errors: Union[bool, str, Callable[[OutputParserException], str]] = (
|
|
1082
|
+
False
|
|
1083
|
+
)
|
|
949
1084
|
"""How to handle errors raised by the agent's output parser.
|
|
950
1085
|
Defaults to `False`, which raises the error.
|
|
951
1086
|
If `true`, the error will be sent back to the LLM as an observation.
|
|
@@ -957,6 +1092,9 @@ class AgentExecutor(Chain):
|
|
|
957
1092
|
trim_intermediate_steps: Union[
|
|
958
1093
|
int, Callable[[List[Tuple[AgentAction, str]]], List[Tuple[AgentAction, str]]]
|
|
959
1094
|
] = -1
|
|
1095
|
+
"""How to trim the intermediate steps before returning them.
|
|
1096
|
+
Defaults to -1, which means no trimming.
|
|
1097
|
+
"""
|
|
960
1098
|
|
|
961
1099
|
@classmethod
|
|
962
1100
|
def from_agent_and_tools(
|
|
@@ -966,7 +1104,17 @@ class AgentExecutor(Chain):
|
|
|
966
1104
|
callbacks: Callbacks = None,
|
|
967
1105
|
**kwargs: Any,
|
|
968
1106
|
) -> AgentExecutor:
|
|
969
|
-
"""Create from agent and tools.
|
|
1107
|
+
"""Create from agent and tools.
|
|
1108
|
+
|
|
1109
|
+
Args:
|
|
1110
|
+
agent: Agent to use.
|
|
1111
|
+
tools: Tools to use.
|
|
1112
|
+
callbacks: Callbacks to use.
|
|
1113
|
+
**kwargs: Additional arguments.
|
|
1114
|
+
|
|
1115
|
+
Returns:
|
|
1116
|
+
AgentExecutor: Agent executor object.
|
|
1117
|
+
"""
|
|
970
1118
|
return cls(
|
|
971
1119
|
agent=agent,
|
|
972
1120
|
tools=tools,
|
|
@@ -974,9 +1122,19 @@ class AgentExecutor(Chain):
|
|
|
974
1122
|
**kwargs,
|
|
975
1123
|
)
|
|
976
1124
|
|
|
977
|
-
@root_validator()
|
|
1125
|
+
@root_validator(pre=False, skip_on_failure=True)
|
|
978
1126
|
def validate_tools(cls, values: Dict) -> Dict:
|
|
979
|
-
"""Validate that tools are compatible with agent.
|
|
1127
|
+
"""Validate that tools are compatible with agent.
|
|
1128
|
+
|
|
1129
|
+
Args:
|
|
1130
|
+
values: Values to validate.
|
|
1131
|
+
|
|
1132
|
+
Returns:
|
|
1133
|
+
Dict: Validated values.
|
|
1134
|
+
|
|
1135
|
+
Raises:
|
|
1136
|
+
ValueError: If allowed tools are different than provided tools.
|
|
1137
|
+
"""
|
|
980
1138
|
agent = values["agent"]
|
|
981
1139
|
tools = values["tools"]
|
|
982
1140
|
allowed_tools = agent.get_allowed_tools()
|
|
@@ -988,9 +1146,19 @@ class AgentExecutor(Chain):
|
|
|
988
1146
|
)
|
|
989
1147
|
return values
|
|
990
1148
|
|
|
991
|
-
@root_validator()
|
|
1149
|
+
@root_validator(pre=False, skip_on_failure=True)
|
|
992
1150
|
def validate_return_direct_tool(cls, values: Dict) -> Dict:
|
|
993
|
-
"""Validate that tools are compatible with agent.
|
|
1151
|
+
"""Validate that tools are compatible with agent.
|
|
1152
|
+
|
|
1153
|
+
Args:
|
|
1154
|
+
values: Values to validate.
|
|
1155
|
+
|
|
1156
|
+
Returns:
|
|
1157
|
+
Dict: Validated values.
|
|
1158
|
+
|
|
1159
|
+
Raises:
|
|
1160
|
+
ValueError: If tools that have `return_direct=True` are not allowed.
|
|
1161
|
+
"""
|
|
994
1162
|
agent = values["agent"]
|
|
995
1163
|
tools = values["tools"]
|
|
996
1164
|
if isinstance(agent, BaseMultiActionAgent):
|
|
@@ -1004,9 +1172,16 @@ class AgentExecutor(Chain):
|
|
|
1004
1172
|
|
|
1005
1173
|
@root_validator(pre=True)
|
|
1006
1174
|
def validate_runnable_agent(cls, values: Dict) -> Dict:
|
|
1007
|
-
"""Convert runnable to agent if passed in.
|
|
1008
|
-
|
|
1009
|
-
|
|
1175
|
+
"""Convert runnable to agent if passed in.
|
|
1176
|
+
|
|
1177
|
+
Args:
|
|
1178
|
+
values: Values to validate.
|
|
1179
|
+
|
|
1180
|
+
Returns:
|
|
1181
|
+
Dict: Validated values.
|
|
1182
|
+
"""
|
|
1183
|
+
agent = values.get("agent")
|
|
1184
|
+
if agent and isinstance(agent, Runnable):
|
|
1010
1185
|
try:
|
|
1011
1186
|
output_type = agent.OutputType
|
|
1012
1187
|
except Exception as _:
|
|
@@ -1026,7 +1201,14 @@ class AgentExecutor(Chain):
|
|
|
1026
1201
|
return values
|
|
1027
1202
|
|
|
1028
1203
|
def save(self, file_path: Union[Path, str]) -> None:
|
|
1029
|
-
"""Raise error - saving not supported for Agent Executors.
|
|
1204
|
+
"""Raise error - saving not supported for Agent Executors.
|
|
1205
|
+
|
|
1206
|
+
Args:
|
|
1207
|
+
file_path: Path to save to.
|
|
1208
|
+
|
|
1209
|
+
Raises:
|
|
1210
|
+
ValueError: Saving not supported for agent executors.
|
|
1211
|
+
"""
|
|
1030
1212
|
raise ValueError(
|
|
1031
1213
|
"Saving not supported for agent executors. "
|
|
1032
1214
|
"If you are trying to save the agent, please use the "
|
|
@@ -1034,7 +1216,11 @@ class AgentExecutor(Chain):
|
|
|
1034
1216
|
)
|
|
1035
1217
|
|
|
1036
1218
|
def save_agent(self, file_path: Union[Path, str]) -> None:
|
|
1037
|
-
"""Save the underlying agent.
|
|
1219
|
+
"""Save the underlying agent.
|
|
1220
|
+
|
|
1221
|
+
Args:
|
|
1222
|
+
file_path: Path to save to.
|
|
1223
|
+
"""
|
|
1038
1224
|
return self.agent.save(file_path)
|
|
1039
1225
|
|
|
1040
1226
|
def iter(
|
|
@@ -1045,7 +1231,17 @@ class AgentExecutor(Chain):
|
|
|
1045
1231
|
include_run_info: bool = False,
|
|
1046
1232
|
async_: bool = False, # arg kept for backwards compat, but ignored
|
|
1047
1233
|
) -> AgentExecutorIterator:
|
|
1048
|
-
"""Enables iteration over steps taken to reach final output.
|
|
1234
|
+
"""Enables iteration over steps taken to reach final output.
|
|
1235
|
+
|
|
1236
|
+
Args:
|
|
1237
|
+
inputs: Inputs to the agent.
|
|
1238
|
+
callbacks: Callbacks to run.
|
|
1239
|
+
include_run_info: Whether to include run info.
|
|
1240
|
+
async_: Whether to run async. (Ignored)
|
|
1241
|
+
|
|
1242
|
+
Returns:
|
|
1243
|
+
AgentExecutorIterator: Agent executor iterator object.
|
|
1244
|
+
"""
|
|
1049
1245
|
return AgentExecutorIterator(
|
|
1050
1246
|
self,
|
|
1051
1247
|
inputs,
|
|
@@ -1074,7 +1270,14 @@ class AgentExecutor(Chain):
|
|
|
1074
1270
|
return self.agent.return_values
|
|
1075
1271
|
|
|
1076
1272
|
def lookup_tool(self, name: str) -> BaseTool:
|
|
1077
|
-
"""Lookup tool by name.
|
|
1273
|
+
"""Lookup tool by name.
|
|
1274
|
+
|
|
1275
|
+
Args:
|
|
1276
|
+
name: Name of tool.
|
|
1277
|
+
|
|
1278
|
+
Returns:
|
|
1279
|
+
BaseTool: Tool object.
|
|
1280
|
+
"""
|
|
1078
1281
|
return {tool.name: tool for tool in self.tools}[name]
|
|
1079
1282
|
|
|
1080
1283
|
def _should_continue(self, iterations: int, time_elapsed: float) -> bool:
|
|
@@ -1463,7 +1666,7 @@ class AgentExecutor(Chain):
|
|
|
1463
1666
|
inputs: Dict[str, str],
|
|
1464
1667
|
run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
|
|
1465
1668
|
) -> Dict[str, str]:
|
|
1466
|
-
"""
|
|
1669
|
+
"""Async run text through and get agent response."""
|
|
1467
1670
|
# Construct a mapping of tool name to tool for easy lookup
|
|
1468
1671
|
name_to_tool_map = {tool.name: tool for tool in self.tools}
|
|
1469
1672
|
# We construct a mapping from each tool to a color, used for logging.
|
|
@@ -1557,7 +1760,16 @@ class AgentExecutor(Chain):
|
|
|
1557
1760
|
config: Optional[RunnableConfig] = None,
|
|
1558
1761
|
**kwargs: Any,
|
|
1559
1762
|
) -> Iterator[AddableDict]:
|
|
1560
|
-
"""Enables streaming over steps taken to reach final output.
|
|
1763
|
+
"""Enables streaming over steps taken to reach final output.
|
|
1764
|
+
|
|
1765
|
+
Args:
|
|
1766
|
+
input: Input to the agent.
|
|
1767
|
+
config: Config to use.
|
|
1768
|
+
**kwargs: Additional arguments.
|
|
1769
|
+
|
|
1770
|
+
Yields:
|
|
1771
|
+
AddableDict: Addable dictionary.
|
|
1772
|
+
"""
|
|
1561
1773
|
config = ensure_config(config)
|
|
1562
1774
|
iterator = AgentExecutorIterator(
|
|
1563
1775
|
self,
|
|
@@ -1579,7 +1791,17 @@ class AgentExecutor(Chain):
|
|
|
1579
1791
|
config: Optional[RunnableConfig] = None,
|
|
1580
1792
|
**kwargs: Any,
|
|
1581
1793
|
) -> AsyncIterator[AddableDict]:
|
|
1582
|
-
"""
|
|
1794
|
+
"""Async enables streaming over steps taken to reach final output.
|
|
1795
|
+
|
|
1796
|
+
Args:
|
|
1797
|
+
input: Input to the agent.
|
|
1798
|
+
config: Config to use.
|
|
1799
|
+
**kwargs: Additional arguments.
|
|
1800
|
+
|
|
1801
|
+
Yields:
|
|
1802
|
+
AddableDict: Addable dictionary.
|
|
1803
|
+
"""
|
|
1804
|
+
|
|
1583
1805
|
config = ensure_config(config)
|
|
1584
1806
|
iterator = AgentExecutorIterator(
|
|
1585
1807
|
self,
|