langchain-core 1.0.0a5__py3-none-any.whl → 1.0.0a7__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-core might be problematic. Click here for more details.
- langchain_core/_api/__init__.py +3 -3
- langchain_core/_api/beta_decorator.py +6 -6
- langchain_core/_api/deprecation.py +21 -29
- langchain_core/_api/path.py +3 -6
- langchain_core/_import_utils.py +2 -3
- langchain_core/agents.py +10 -11
- langchain_core/caches.py +7 -7
- langchain_core/callbacks/base.py +91 -91
- langchain_core/callbacks/file.py +11 -11
- langchain_core/callbacks/manager.py +86 -89
- langchain_core/callbacks/stdout.py +8 -8
- langchain_core/callbacks/usage.py +4 -4
- langchain_core/chat_history.py +1 -37
- langchain_core/document_loaders/base.py +2 -2
- langchain_core/document_loaders/langsmith.py +15 -15
- langchain_core/documents/base.py +16 -16
- langchain_core/documents/compressor.py +4 -4
- langchain_core/example_selectors/length_based.py +1 -1
- langchain_core/example_selectors/semantic_similarity.py +17 -19
- langchain_core/exceptions.py +3 -3
- langchain_core/globals.py +3 -151
- langchain_core/indexing/api.py +44 -43
- langchain_core/indexing/base.py +30 -30
- langchain_core/indexing/in_memory.py +3 -3
- langchain_core/language_models/_utils.py +5 -7
- langchain_core/language_models/base.py +18 -132
- langchain_core/language_models/chat_models.py +118 -227
- langchain_core/language_models/fake.py +11 -11
- langchain_core/language_models/fake_chat_models.py +35 -29
- langchain_core/language_models/llms.py +91 -201
- langchain_core/load/dump.py +1 -1
- langchain_core/load/load.py +11 -12
- langchain_core/load/mapping.py +2 -4
- langchain_core/load/serializable.py +2 -4
- langchain_core/messages/ai.py +17 -20
- langchain_core/messages/base.py +28 -26
- langchain_core/messages/block_translators/__init__.py +17 -7
- langchain_core/messages/block_translators/anthropic.py +3 -3
- langchain_core/messages/block_translators/bedrock_converse.py +2 -2
- langchain_core/messages/block_translators/google_genai.py +502 -20
- langchain_core/messages/block_translators/langchain_v0.py +2 -2
- langchain_core/messages/block_translators/openai.py +6 -6
- langchain_core/messages/content.py +120 -124
- langchain_core/messages/human.py +7 -7
- langchain_core/messages/system.py +7 -7
- langchain_core/messages/tool.py +24 -24
- langchain_core/messages/utils.py +67 -79
- langchain_core/output_parsers/base.py +12 -14
- langchain_core/output_parsers/json.py +4 -4
- langchain_core/output_parsers/list.py +3 -5
- langchain_core/output_parsers/openai_functions.py +3 -3
- langchain_core/output_parsers/openai_tools.py +3 -3
- langchain_core/output_parsers/pydantic.py +2 -2
- langchain_core/output_parsers/transform.py +13 -15
- langchain_core/output_parsers/xml.py +7 -9
- langchain_core/outputs/chat_generation.py +4 -4
- langchain_core/outputs/chat_result.py +1 -3
- langchain_core/outputs/generation.py +2 -2
- langchain_core/outputs/llm_result.py +5 -5
- langchain_core/prompts/__init__.py +1 -5
- langchain_core/prompts/base.py +10 -15
- langchain_core/prompts/chat.py +31 -82
- langchain_core/prompts/dict.py +2 -2
- langchain_core/prompts/few_shot.py +5 -5
- langchain_core/prompts/few_shot_with_templates.py +4 -4
- langchain_core/prompts/loading.py +3 -5
- langchain_core/prompts/prompt.py +4 -16
- langchain_core/prompts/string.py +2 -1
- langchain_core/prompts/structured.py +16 -23
- langchain_core/rate_limiters.py +3 -4
- langchain_core/retrievers.py +14 -14
- langchain_core/runnables/base.py +938 -1054
- langchain_core/runnables/branch.py +36 -40
- langchain_core/runnables/config.py +27 -35
- langchain_core/runnables/configurable.py +108 -124
- langchain_core/runnables/fallbacks.py +76 -72
- langchain_core/runnables/graph.py +39 -45
- langchain_core/runnables/graph_ascii.py +9 -11
- langchain_core/runnables/graph_mermaid.py +18 -19
- langchain_core/runnables/graph_png.py +8 -9
- langchain_core/runnables/history.py +114 -127
- langchain_core/runnables/passthrough.py +113 -139
- langchain_core/runnables/retry.py +43 -48
- langchain_core/runnables/router.py +23 -28
- langchain_core/runnables/schema.py +42 -44
- langchain_core/runnables/utils.py +28 -31
- langchain_core/stores.py +9 -13
- langchain_core/structured_query.py +8 -8
- langchain_core/tools/base.py +63 -115
- langchain_core/tools/convert.py +31 -35
- langchain_core/tools/render.py +1 -1
- langchain_core/tools/retriever.py +4 -4
- langchain_core/tools/simple.py +13 -17
- langchain_core/tools/structured.py +12 -15
- langchain_core/tracers/base.py +62 -64
- langchain_core/tracers/context.py +17 -35
- langchain_core/tracers/core.py +49 -53
- langchain_core/tracers/evaluation.py +11 -11
- langchain_core/tracers/event_stream.py +58 -60
- langchain_core/tracers/langchain.py +13 -13
- langchain_core/tracers/log_stream.py +22 -24
- langchain_core/tracers/root_listeners.py +14 -14
- langchain_core/tracers/run_collector.py +2 -4
- langchain_core/tracers/schemas.py +8 -8
- langchain_core/tracers/stdout.py +2 -1
- langchain_core/utils/__init__.py +0 -3
- langchain_core/utils/_merge.py +2 -2
- langchain_core/utils/aiter.py +24 -28
- langchain_core/utils/env.py +4 -4
- langchain_core/utils/function_calling.py +31 -41
- langchain_core/utils/html.py +3 -4
- langchain_core/utils/input.py +3 -3
- langchain_core/utils/iter.py +15 -19
- langchain_core/utils/json.py +3 -2
- langchain_core/utils/json_schema.py +6 -6
- langchain_core/utils/mustache.py +3 -5
- langchain_core/utils/pydantic.py +16 -18
- langchain_core/utils/usage.py +1 -1
- langchain_core/utils/utils.py +29 -29
- langchain_core/vectorstores/base.py +18 -21
- langchain_core/vectorstores/in_memory.py +14 -87
- langchain_core/vectorstores/utils.py +2 -2
- langchain_core/version.py +1 -1
- {langchain_core-1.0.0a5.dist-info → langchain_core-1.0.0a7.dist-info}/METADATA +10 -31
- langchain_core-1.0.0a7.dist-info/RECORD +176 -0
- {langchain_core-1.0.0a5.dist-info → langchain_core-1.0.0a7.dist-info}/WHEEL +1 -1
- langchain_core/messages/block_translators/ollama.py +0 -47
- langchain_core/prompts/pipeline.py +0 -138
- langchain_core/tracers/langchain_v1.py +0 -31
- langchain_core/utils/loading.py +0 -35
- langchain_core-1.0.0a5.dist-info/RECORD +0 -181
- langchain_core-1.0.0a5.dist-info/entry_points.txt +0 -4
langchain_core/tools/base.py
CHANGED
|
@@ -8,16 +8,14 @@ import json
|
|
|
8
8
|
import typing
|
|
9
9
|
import warnings
|
|
10
10
|
from abc import ABC, abstractmethod
|
|
11
|
+
from collections.abc import Callable
|
|
11
12
|
from inspect import signature
|
|
12
13
|
from typing import (
|
|
13
14
|
TYPE_CHECKING,
|
|
14
15
|
Annotated,
|
|
15
16
|
Any,
|
|
16
|
-
Callable,
|
|
17
17
|
Literal,
|
|
18
|
-
Optional,
|
|
19
18
|
TypeVar,
|
|
20
|
-
Union,
|
|
21
19
|
cast,
|
|
22
20
|
get_args,
|
|
23
21
|
get_origin,
|
|
@@ -31,7 +29,6 @@ from pydantic import (
|
|
|
31
29
|
PydanticDeprecationWarning,
|
|
32
30
|
SkipValidation,
|
|
33
31
|
ValidationError,
|
|
34
|
-
model_validator,
|
|
35
32
|
validate_arguments,
|
|
36
33
|
)
|
|
37
34
|
from pydantic.v1 import BaseModel as BaseModelV1
|
|
@@ -39,10 +36,8 @@ from pydantic.v1 import ValidationError as ValidationErrorV1
|
|
|
39
36
|
from pydantic.v1 import validate_arguments as validate_arguments_v1
|
|
40
37
|
from typing_extensions import override
|
|
41
38
|
|
|
42
|
-
from langchain_core._api import deprecated
|
|
43
39
|
from langchain_core.callbacks import (
|
|
44
40
|
AsyncCallbackManager,
|
|
45
|
-
BaseCallbackManager,
|
|
46
41
|
CallbackManager,
|
|
47
42
|
Callbacks,
|
|
48
43
|
)
|
|
@@ -82,6 +77,7 @@ TOOL_MESSAGE_BLOCK_TYPES = (
|
|
|
82
77
|
"search_result",
|
|
83
78
|
"custom_tool_call_output",
|
|
84
79
|
"document",
|
|
80
|
+
"file",
|
|
85
81
|
)
|
|
86
82
|
|
|
87
83
|
|
|
@@ -284,7 +280,7 @@ def create_schema_from_function(
|
|
|
284
280
|
model_name: str,
|
|
285
281
|
func: Callable,
|
|
286
282
|
*,
|
|
287
|
-
filter_args:
|
|
283
|
+
filter_args: Sequence[str] | None = None,
|
|
288
284
|
parse_docstring: bool = False,
|
|
289
285
|
error_on_invalid_docstring: bool = False,
|
|
290
286
|
include_injected: bool = True,
|
|
@@ -389,10 +385,10 @@ class ToolException(Exception): # noqa: N818
|
|
|
389
385
|
"""
|
|
390
386
|
|
|
391
387
|
|
|
392
|
-
ArgsSchema =
|
|
388
|
+
ArgsSchema = TypeBaseModel | dict[str, Any]
|
|
393
389
|
|
|
394
390
|
|
|
395
|
-
class BaseTool(RunnableSerializable[
|
|
391
|
+
class BaseTool(RunnableSerializable[str | dict | ToolCall, Any]):
|
|
396
392
|
"""Base class for all LangChain tools.
|
|
397
393
|
|
|
398
394
|
This abstract class defines the interface that all LangChain tools must implement.
|
|
@@ -440,7 +436,7 @@ class ChildTool(BaseTool):
|
|
|
440
436
|
You can provide few-shot examples as a part of the description.
|
|
441
437
|
"""
|
|
442
438
|
|
|
443
|
-
args_schema: Annotated[
|
|
439
|
+
args_schema: Annotated[ArgsSchema | None, SkipValidation()] = Field(
|
|
444
440
|
default=None, description="The tool schema."
|
|
445
441
|
)
|
|
446
442
|
"""Pydantic model class to validate and parse the tool's input arguments.
|
|
@@ -463,36 +459,25 @@ class ChildTool(BaseTool):
|
|
|
463
459
|
callbacks: Callbacks = Field(default=None, exclude=True)
|
|
464
460
|
"""Callbacks to be called during tool execution."""
|
|
465
461
|
|
|
466
|
-
|
|
467
|
-
name="callback_manager", since="0.1.7", removal="1.0", alternative="callbacks"
|
|
468
|
-
)(
|
|
469
|
-
Field(
|
|
470
|
-
default=None,
|
|
471
|
-
exclude=True,
|
|
472
|
-
description="Callback manager to add to the run trace.",
|
|
473
|
-
)
|
|
474
|
-
)
|
|
475
|
-
tags: Optional[list[str]] = None
|
|
462
|
+
tags: list[str] | None = None
|
|
476
463
|
"""Optional list of tags associated with the tool. Defaults to None.
|
|
477
464
|
These tags will be associated with each call to this tool,
|
|
478
465
|
and passed as arguments to the handlers defined in `callbacks`.
|
|
479
466
|
You can use these to eg identify a specific instance of a tool with its use case.
|
|
480
467
|
"""
|
|
481
|
-
metadata:
|
|
468
|
+
metadata: dict[str, Any] | None = None
|
|
482
469
|
"""Optional metadata associated with the tool. Defaults to None.
|
|
483
470
|
This metadata will be associated with each call to this tool,
|
|
484
471
|
and passed as arguments to the handlers defined in `callbacks`.
|
|
485
472
|
You can use these to eg identify a specific instance of a tool with its use case.
|
|
486
473
|
"""
|
|
487
474
|
|
|
488
|
-
handle_tool_error:
|
|
489
|
-
False
|
|
490
|
-
)
|
|
475
|
+
handle_tool_error: bool | str | Callable[[ToolException], str] | None = False
|
|
491
476
|
"""Handle the content of the ToolException thrown."""
|
|
492
477
|
|
|
493
|
-
handle_validation_error:
|
|
494
|
-
|
|
495
|
-
|
|
478
|
+
handle_validation_error: (
|
|
479
|
+
bool | str | Callable[[ValidationError | ValidationErrorV1], str] | None
|
|
480
|
+
) = False
|
|
496
481
|
"""Handle the content of the ValidationError thrown."""
|
|
497
482
|
|
|
498
483
|
response_format: Literal["content", "content_and_artifact"] = "content"
|
|
@@ -581,9 +566,7 @@ class ChildTool(BaseTool):
|
|
|
581
566
|
# --- Runnable ---
|
|
582
567
|
|
|
583
568
|
@override
|
|
584
|
-
def get_input_schema(
|
|
585
|
-
self, config: Optional[RunnableConfig] = None
|
|
586
|
-
) -> type[BaseModel]:
|
|
569
|
+
def get_input_schema(self, config: RunnableConfig | None = None) -> type[BaseModel]:
|
|
587
570
|
"""The tool's input schema.
|
|
588
571
|
|
|
589
572
|
Args:
|
|
@@ -601,8 +584,8 @@ class ChildTool(BaseTool):
|
|
|
601
584
|
@override
|
|
602
585
|
def invoke(
|
|
603
586
|
self,
|
|
604
|
-
input:
|
|
605
|
-
config:
|
|
587
|
+
input: str | dict | ToolCall,
|
|
588
|
+
config: RunnableConfig | None = None,
|
|
606
589
|
**kwargs: Any,
|
|
607
590
|
) -> Any:
|
|
608
591
|
tool_input, kwargs = _prep_run_args(input, config, **kwargs)
|
|
@@ -611,8 +594,8 @@ class ChildTool(BaseTool):
|
|
|
611
594
|
@override
|
|
612
595
|
async def ainvoke(
|
|
613
596
|
self,
|
|
614
|
-
input:
|
|
615
|
-
config:
|
|
597
|
+
input: str | dict | ToolCall,
|
|
598
|
+
config: RunnableConfig | None = None,
|
|
616
599
|
**kwargs: Any,
|
|
617
600
|
) -> Any:
|
|
618
601
|
tool_input, kwargs = _prep_run_args(input, config, **kwargs)
|
|
@@ -621,8 +604,8 @@ class ChildTool(BaseTool):
|
|
|
621
604
|
# --- Tool ---
|
|
622
605
|
|
|
623
606
|
def _parse_input(
|
|
624
|
-
self, tool_input:
|
|
625
|
-
) ->
|
|
607
|
+
self, tool_input: str | dict, tool_call_id: str | None
|
|
608
|
+
) -> str | dict[str, Any]:
|
|
626
609
|
"""Parse and validate tool input using the args schema.
|
|
627
610
|
|
|
628
611
|
Args:
|
|
@@ -699,26 +682,6 @@ class ChildTool(BaseTool):
|
|
|
699
682
|
}
|
|
700
683
|
return tool_input
|
|
701
684
|
|
|
702
|
-
@model_validator(mode="before")
|
|
703
|
-
@classmethod
|
|
704
|
-
def raise_deprecation(cls, values: dict) -> Any:
|
|
705
|
-
"""Raise deprecation warning if callback_manager is used.
|
|
706
|
-
|
|
707
|
-
Args:
|
|
708
|
-
values: The values to validate.
|
|
709
|
-
|
|
710
|
-
Returns:
|
|
711
|
-
The validated values.
|
|
712
|
-
"""
|
|
713
|
-
if values.get("callback_manager") is not None:
|
|
714
|
-
warnings.warn(
|
|
715
|
-
"callback_manager is deprecated. Please use callbacks instead.",
|
|
716
|
-
DeprecationWarning,
|
|
717
|
-
stacklevel=6,
|
|
718
|
-
)
|
|
719
|
-
values["callbacks"] = values.pop("callback_manager", None)
|
|
720
|
-
return values
|
|
721
|
-
|
|
722
685
|
@abstractmethod
|
|
723
686
|
def _run(self, *args: Any, **kwargs: Any) -> Any:
|
|
724
687
|
"""Use the tool.
|
|
@@ -746,7 +709,7 @@ class ChildTool(BaseTool):
|
|
|
746
709
|
return await run_in_executor(None, self._run, *args, **kwargs)
|
|
747
710
|
|
|
748
711
|
def _to_args_and_kwargs(
|
|
749
|
-
self, tool_input:
|
|
712
|
+
self, tool_input: str | dict, tool_call_id: str | None
|
|
750
713
|
) -> tuple[tuple, dict]:
|
|
751
714
|
"""Convert tool input to positional and keyword arguments.
|
|
752
715
|
|
|
@@ -786,18 +749,18 @@ class ChildTool(BaseTool):
|
|
|
786
749
|
|
|
787
750
|
def run(
|
|
788
751
|
self,
|
|
789
|
-
tool_input:
|
|
790
|
-
verbose:
|
|
791
|
-
start_color:
|
|
792
|
-
color:
|
|
752
|
+
tool_input: str | dict[str, Any],
|
|
753
|
+
verbose: bool | None = None, # noqa: FBT001
|
|
754
|
+
start_color: str | None = "green",
|
|
755
|
+
color: str | None = "green",
|
|
793
756
|
callbacks: Callbacks = None,
|
|
794
757
|
*,
|
|
795
|
-
tags:
|
|
796
|
-
metadata:
|
|
797
|
-
run_name:
|
|
798
|
-
run_id:
|
|
799
|
-
config:
|
|
800
|
-
tool_call_id:
|
|
758
|
+
tags: list[str] | None = None,
|
|
759
|
+
metadata: dict[str, Any] | None = None,
|
|
760
|
+
run_name: str | None = None,
|
|
761
|
+
run_id: uuid.UUID | None = None,
|
|
762
|
+
config: RunnableConfig | None = None,
|
|
763
|
+
tool_call_id: str | None = None,
|
|
801
764
|
**kwargs: Any,
|
|
802
765
|
) -> Any:
|
|
803
766
|
"""Run the tool.
|
|
@@ -849,7 +812,7 @@ class ChildTool(BaseTool):
|
|
|
849
812
|
content = None
|
|
850
813
|
artifact = None
|
|
851
814
|
status = "success"
|
|
852
|
-
error_to_raise:
|
|
815
|
+
error_to_raise: Exception | KeyboardInterrupt | None = None
|
|
853
816
|
try:
|
|
854
817
|
child_config = patch_config(config, callbacks=run_manager.get_child())
|
|
855
818
|
with set_config_context(child_config) as context:
|
|
@@ -898,18 +861,18 @@ class ChildTool(BaseTool):
|
|
|
898
861
|
|
|
899
862
|
async def arun(
|
|
900
863
|
self,
|
|
901
|
-
tool_input:
|
|
902
|
-
verbose:
|
|
903
|
-
start_color:
|
|
904
|
-
color:
|
|
864
|
+
tool_input: str | dict,
|
|
865
|
+
verbose: bool | None = None, # noqa: FBT001
|
|
866
|
+
start_color: str | None = "green",
|
|
867
|
+
color: str | None = "green",
|
|
905
868
|
callbacks: Callbacks = None,
|
|
906
869
|
*,
|
|
907
|
-
tags:
|
|
908
|
-
metadata:
|
|
909
|
-
run_name:
|
|
910
|
-
run_id:
|
|
911
|
-
config:
|
|
912
|
-
tool_call_id:
|
|
870
|
+
tags: list[str] | None = None,
|
|
871
|
+
metadata: dict[str, Any] | None = None,
|
|
872
|
+
run_name: str | None = None,
|
|
873
|
+
run_id: uuid.UUID | None = None,
|
|
874
|
+
config: RunnableConfig | None = None,
|
|
875
|
+
tool_call_id: str | None = None,
|
|
913
876
|
**kwargs: Any,
|
|
914
877
|
) -> Any:
|
|
915
878
|
"""Run the tool asynchronously.
|
|
@@ -959,7 +922,7 @@ class ChildTool(BaseTool):
|
|
|
959
922
|
content = None
|
|
960
923
|
artifact = None
|
|
961
924
|
status = "success"
|
|
962
|
-
error_to_raise:
|
|
925
|
+
error_to_raise: Exception | KeyboardInterrupt | None = None
|
|
963
926
|
try:
|
|
964
927
|
tool_args, tool_kwargs = self._to_args_and_kwargs(tool_input, tool_call_id)
|
|
965
928
|
child_config = patch_config(config, callbacks=run_manager.get_child())
|
|
@@ -1010,19 +973,6 @@ class ChildTool(BaseTool):
|
|
|
1010
973
|
await run_manager.on_tool_end(output, color=color, name=self.name, **kwargs)
|
|
1011
974
|
return output
|
|
1012
975
|
|
|
1013
|
-
@deprecated("0.1.47", alternative="invoke", removal="1.0")
|
|
1014
|
-
def __call__(self, tool_input: str, callbacks: Callbacks = None) -> str:
|
|
1015
|
-
"""Make tool callable (deprecated).
|
|
1016
|
-
|
|
1017
|
-
Args:
|
|
1018
|
-
tool_input: The input to the tool.
|
|
1019
|
-
callbacks: Callbacks to use during execution.
|
|
1020
|
-
|
|
1021
|
-
Returns:
|
|
1022
|
-
The tool's output.
|
|
1023
|
-
"""
|
|
1024
|
-
return self.run(tool_input, callbacks=callbacks)
|
|
1025
|
-
|
|
1026
976
|
|
|
1027
977
|
def _is_tool_call(x: Any) -> bool:
|
|
1028
978
|
"""Check if the input is a tool call dictionary.
|
|
@@ -1037,11 +987,9 @@ def _is_tool_call(x: Any) -> bool:
|
|
|
1037
987
|
|
|
1038
988
|
|
|
1039
989
|
def _handle_validation_error(
|
|
1040
|
-
e:
|
|
990
|
+
e: ValidationError | ValidationErrorV1,
|
|
1041
991
|
*,
|
|
1042
|
-
flag:
|
|
1043
|
-
Literal[True], str, Callable[[Union[ValidationError, ValidationErrorV1]], str]
|
|
1044
|
-
],
|
|
992
|
+
flag: Literal[True] | str | Callable[[ValidationError | ValidationErrorV1], str],
|
|
1045
993
|
) -> str:
|
|
1046
994
|
"""Handle validation errors based on the configured flag.
|
|
1047
995
|
|
|
@@ -1073,7 +1021,7 @@ def _handle_validation_error(
|
|
|
1073
1021
|
def _handle_tool_error(
|
|
1074
1022
|
e: ToolException,
|
|
1075
1023
|
*,
|
|
1076
|
-
flag:
|
|
1024
|
+
flag: Literal[True] | str | Callable[[ToolException], str] | None,
|
|
1077
1025
|
) -> str:
|
|
1078
1026
|
"""Handle tool execution errors based on the configured flag.
|
|
1079
1027
|
|
|
@@ -1103,10 +1051,10 @@ def _handle_tool_error(
|
|
|
1103
1051
|
|
|
1104
1052
|
|
|
1105
1053
|
def _prep_run_args(
|
|
1106
|
-
value:
|
|
1107
|
-
config:
|
|
1054
|
+
value: str | dict | ToolCall,
|
|
1055
|
+
config: RunnableConfig | None,
|
|
1108
1056
|
**kwargs: Any,
|
|
1109
|
-
) -> tuple[
|
|
1057
|
+
) -> tuple[str | dict, dict]:
|
|
1110
1058
|
"""Prepare arguments for tool execution.
|
|
1111
1059
|
|
|
1112
1060
|
Args:
|
|
@@ -1119,11 +1067,11 @@ def _prep_run_args(
|
|
|
1119
1067
|
"""
|
|
1120
1068
|
config = ensure_config(config)
|
|
1121
1069
|
if _is_tool_call(value):
|
|
1122
|
-
tool_call_id:
|
|
1123
|
-
tool_input:
|
|
1070
|
+
tool_call_id: str | None = cast("ToolCall", value)["id"]
|
|
1071
|
+
tool_input: str | dict = cast("ToolCall", value)["args"].copy()
|
|
1124
1072
|
else:
|
|
1125
1073
|
tool_call_id = None
|
|
1126
|
-
tool_input = cast("
|
|
1074
|
+
tool_input = cast("str | dict", value)
|
|
1127
1075
|
return (
|
|
1128
1076
|
tool_input,
|
|
1129
1077
|
dict(
|
|
@@ -1142,10 +1090,10 @@ def _prep_run_args(
|
|
|
1142
1090
|
def _format_output(
|
|
1143
1091
|
content: Any,
|
|
1144
1092
|
artifact: Any,
|
|
1145
|
-
tool_call_id:
|
|
1093
|
+
tool_call_id: str | None,
|
|
1146
1094
|
name: str,
|
|
1147
1095
|
status: str,
|
|
1148
|
-
) ->
|
|
1096
|
+
) -> ToolOutputMixin | Any:
|
|
1149
1097
|
"""Format tool output as a ToolMessage if appropriate.
|
|
1150
1098
|
|
|
1151
1099
|
Args:
|
|
@@ -1220,7 +1168,7 @@ def _stringify(content: Any) -> str:
|
|
|
1220
1168
|
return str(content)
|
|
1221
1169
|
|
|
1222
1170
|
|
|
1223
|
-
def _get_type_hints(func: Callable) ->
|
|
1171
|
+
def _get_type_hints(func: Callable) -> dict[str, type] | None:
|
|
1224
1172
|
"""Get type hints from a function, handling partial functions.
|
|
1225
1173
|
|
|
1226
1174
|
Args:
|
|
@@ -1237,7 +1185,7 @@ def _get_type_hints(func: Callable) -> Optional[dict[str, type]]:
|
|
|
1237
1185
|
return None
|
|
1238
1186
|
|
|
1239
1187
|
|
|
1240
|
-
def _get_runnable_config_param(func: Callable) ->
|
|
1188
|
+
def _get_runnable_config_param(func: Callable) -> str | None:
|
|
1241
1189
|
"""Find the parameter name for RunnableConfig in a function.
|
|
1242
1190
|
|
|
1243
1191
|
Args:
|
|
@@ -1291,7 +1239,7 @@ class InjectedToolCallId(InjectedToolArg):
|
|
|
1291
1239
|
|
|
1292
1240
|
|
|
1293
1241
|
def _is_injected_arg_type(
|
|
1294
|
-
type_:
|
|
1242
|
+
type_: type | TypeVar, injected_type: type[InjectedToolArg] | None = None
|
|
1295
1243
|
) -> bool:
|
|
1296
1244
|
"""Check if a type annotation indicates an injected argument.
|
|
1297
1245
|
|
|
@@ -1311,8 +1259,8 @@ def _is_injected_arg_type(
|
|
|
1311
1259
|
|
|
1312
1260
|
|
|
1313
1261
|
def get_all_basemodel_annotations(
|
|
1314
|
-
cls:
|
|
1315
|
-
) -> dict[str,
|
|
1262
|
+
cls: TypeBaseModel | Any, *, default_to_bound: bool = True
|
|
1263
|
+
) -> dict[str, type | TypeVar]:
|
|
1316
1264
|
"""Get all annotations from a Pydantic BaseModel and its parents.
|
|
1317
1265
|
|
|
1318
1266
|
Args:
|
|
@@ -1327,7 +1275,7 @@ def get_all_basemodel_annotations(
|
|
|
1327
1275
|
fields = get_fields(cls)
|
|
1328
1276
|
alias_map = {field.alias: name for name, field in fields.items() if field.alias}
|
|
1329
1277
|
|
|
1330
|
-
annotations: dict[str,
|
|
1278
|
+
annotations: dict[str, type | TypeVar] = {}
|
|
1331
1279
|
for name, param in inspect.signature(cls).parameters.items():
|
|
1332
1280
|
# Exclude hidden init args added by pydantic Config. For example if
|
|
1333
1281
|
# BaseModel(extra="allow") then "extra_data" will part of init sig.
|
|
@@ -1368,7 +1316,7 @@ def get_all_basemodel_annotations(
|
|
|
1368
1316
|
# generic_type_vars = (type vars in Baz)
|
|
1369
1317
|
# generic_map = {type var in Baz: str}
|
|
1370
1318
|
generic_type_vars: tuple = getattr(parent_origin, "__parameters__", ())
|
|
1371
|
-
generic_map = dict(zip(generic_type_vars, get_args(parent)))
|
|
1319
|
+
generic_map = dict(zip(generic_type_vars, get_args(parent), strict=False))
|
|
1372
1320
|
for field in getattr(parent_origin, "__annotations__", {}):
|
|
1373
1321
|
annotations[field] = _replace_type_vars(
|
|
1374
1322
|
annotations[field], generic_map, default_to_bound=default_to_bound
|
|
@@ -1381,11 +1329,11 @@ def get_all_basemodel_annotations(
|
|
|
1381
1329
|
|
|
1382
1330
|
|
|
1383
1331
|
def _replace_type_vars(
|
|
1384
|
-
type_:
|
|
1385
|
-
generic_map:
|
|
1332
|
+
type_: type | TypeVar,
|
|
1333
|
+
generic_map: dict[TypeVar, type] | None = None,
|
|
1386
1334
|
*,
|
|
1387
1335
|
default_to_bound: bool = True,
|
|
1388
|
-
) ->
|
|
1336
|
+
) -> type | TypeVar:
|
|
1389
1337
|
"""Replace TypeVars in a type annotation with concrete types.
|
|
1390
1338
|
|
|
1391
1339
|
Args:
|
langchain_core/tools/convert.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"""Convert functions and runnables to tools."""
|
|
2
2
|
|
|
3
3
|
import inspect
|
|
4
|
-
from
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import Any, Literal, get_type_hints, overload
|
|
5
6
|
|
|
6
7
|
from pydantic import BaseModel, Field, create_model
|
|
7
8
|
|
|
@@ -15,14 +16,14 @@ from langchain_core.tools.structured import StructuredTool
|
|
|
15
16
|
@overload
|
|
16
17
|
def tool(
|
|
17
18
|
*,
|
|
18
|
-
description:
|
|
19
|
+
description: str | None = None,
|
|
19
20
|
return_direct: bool = False,
|
|
20
|
-
args_schema:
|
|
21
|
+
args_schema: ArgsSchema | None = None,
|
|
21
22
|
infer_schema: bool = True,
|
|
22
23
|
response_format: Literal["content", "content_and_artifact"] = "content",
|
|
23
24
|
parse_docstring: bool = False,
|
|
24
25
|
error_on_invalid_docstring: bool = True,
|
|
25
|
-
) -> Callable[[
|
|
26
|
+
) -> Callable[[Callable | Runnable], BaseTool]: ...
|
|
26
27
|
|
|
27
28
|
|
|
28
29
|
@overload
|
|
@@ -30,9 +31,9 @@ def tool(
|
|
|
30
31
|
name_or_callable: str,
|
|
31
32
|
runnable: Runnable,
|
|
32
33
|
*,
|
|
33
|
-
description:
|
|
34
|
+
description: str | None = None,
|
|
34
35
|
return_direct: bool = False,
|
|
35
|
-
args_schema:
|
|
36
|
+
args_schema: ArgsSchema | None = None,
|
|
36
37
|
infer_schema: bool = True,
|
|
37
38
|
response_format: Literal["content", "content_and_artifact"] = "content",
|
|
38
39
|
parse_docstring: bool = False,
|
|
@@ -44,9 +45,9 @@ def tool(
|
|
|
44
45
|
def tool(
|
|
45
46
|
name_or_callable: Callable,
|
|
46
47
|
*,
|
|
47
|
-
description:
|
|
48
|
+
description: str | None = None,
|
|
48
49
|
return_direct: bool = False,
|
|
49
|
-
args_schema:
|
|
50
|
+
args_schema: ArgsSchema | None = None,
|
|
50
51
|
infer_schema: bool = True,
|
|
51
52
|
response_format: Literal["content", "content_and_artifact"] = "content",
|
|
52
53
|
parse_docstring: bool = False,
|
|
@@ -58,31 +59,28 @@ def tool(
|
|
|
58
59
|
def tool(
|
|
59
60
|
name_or_callable: str,
|
|
60
61
|
*,
|
|
61
|
-
description:
|
|
62
|
+
description: str | None = None,
|
|
62
63
|
return_direct: bool = False,
|
|
63
|
-
args_schema:
|
|
64
|
+
args_schema: ArgsSchema | None = None,
|
|
64
65
|
infer_schema: bool = True,
|
|
65
66
|
response_format: Literal["content", "content_and_artifact"] = "content",
|
|
66
67
|
parse_docstring: bool = False,
|
|
67
68
|
error_on_invalid_docstring: bool = True,
|
|
68
|
-
) -> Callable[[
|
|
69
|
+
) -> Callable[[Callable | Runnable], BaseTool]: ...
|
|
69
70
|
|
|
70
71
|
|
|
71
72
|
def tool(
|
|
72
|
-
name_or_callable:
|
|
73
|
-
runnable:
|
|
73
|
+
name_or_callable: str | Callable | None = None,
|
|
74
|
+
runnable: Runnable | None = None,
|
|
74
75
|
*args: Any,
|
|
75
|
-
description:
|
|
76
|
+
description: str | None = None,
|
|
76
77
|
return_direct: bool = False,
|
|
77
|
-
args_schema:
|
|
78
|
+
args_schema: ArgsSchema | None = None,
|
|
78
79
|
infer_schema: bool = True,
|
|
79
80
|
response_format: Literal["content", "content_and_artifact"] = "content",
|
|
80
81
|
parse_docstring: bool = False,
|
|
81
82
|
error_on_invalid_docstring: bool = True,
|
|
82
|
-
) ->
|
|
83
|
-
BaseTool,
|
|
84
|
-
Callable[[Union[Callable, Runnable]], BaseTool],
|
|
85
|
-
]:
|
|
83
|
+
) -> BaseTool | Callable[[Callable | Runnable], BaseTool]:
|
|
86
84
|
"""Make tools out of functions, can be used with or without arguments.
|
|
87
85
|
|
|
88
86
|
Args:
|
|
@@ -157,7 +155,7 @@ def tool(
|
|
|
157
155
|
def search_api(query: str) -> tuple[str, dict]:
|
|
158
156
|
return "partial json of results", {"full": "object of results"}
|
|
159
157
|
|
|
160
|
-
|
|
158
|
+
!!! version-added "Added in version 0.2.14"
|
|
161
159
|
|
|
162
160
|
Parse Google-style docstrings:
|
|
163
161
|
|
|
@@ -231,7 +229,7 @@ def tool(
|
|
|
231
229
|
|
|
232
230
|
def _create_tool_factory(
|
|
233
231
|
tool_name: str,
|
|
234
|
-
) -> Callable[[
|
|
232
|
+
) -> Callable[[Callable | Runnable], BaseTool]:
|
|
235
233
|
"""Create a decorator that takes a callable and returns a tool.
|
|
236
234
|
|
|
237
235
|
Args:
|
|
@@ -241,7 +239,7 @@ def tool(
|
|
|
241
239
|
A function that takes a callable or Runnable and returns a tool.
|
|
242
240
|
"""
|
|
243
241
|
|
|
244
|
-
def _tool_factory(dec_func:
|
|
242
|
+
def _tool_factory(dec_func: Callable | Runnable) -> BaseTool:
|
|
245
243
|
tool_description = description
|
|
246
244
|
if isinstance(dec_func, Runnable):
|
|
247
245
|
runnable = dec_func
|
|
@@ -251,18 +249,18 @@ def tool(
|
|
|
251
249
|
raise ValueError(msg)
|
|
252
250
|
|
|
253
251
|
async def ainvoke_wrapper(
|
|
254
|
-
callbacks:
|
|
252
|
+
callbacks: Callbacks | None = None, **kwargs: Any
|
|
255
253
|
) -> Any:
|
|
256
254
|
return await runnable.ainvoke(kwargs, {"callbacks": callbacks})
|
|
257
255
|
|
|
258
256
|
def invoke_wrapper(
|
|
259
|
-
callbacks:
|
|
257
|
+
callbacks: Callbacks | None = None, **kwargs: Any
|
|
260
258
|
) -> Any:
|
|
261
259
|
return runnable.invoke(kwargs, {"callbacks": callbacks})
|
|
262
260
|
|
|
263
261
|
coroutine = ainvoke_wrapper
|
|
264
262
|
func = invoke_wrapper
|
|
265
|
-
schema:
|
|
263
|
+
schema: ArgsSchema | None = runnable.input_schema
|
|
266
264
|
tool_description = description or repr(runnable)
|
|
267
265
|
elif inspect.iscoroutinefunction(dec_func):
|
|
268
266
|
coroutine = dec_func
|
|
@@ -352,7 +350,7 @@ def tool(
|
|
|
352
350
|
# @tool(parse_docstring=True)
|
|
353
351
|
# def my_tool():
|
|
354
352
|
# pass
|
|
355
|
-
def _partial(func:
|
|
353
|
+
def _partial(func: Callable | Runnable) -> BaseTool:
|
|
356
354
|
"""Partial function that takes a callable and returns a tool."""
|
|
357
355
|
name_ = func.get_name() if isinstance(func, Runnable) else func.__name__
|
|
358
356
|
tool_factory = _create_tool_factory(name_)
|
|
@@ -370,7 +368,7 @@ def _get_description_from_runnable(runnable: Runnable) -> str:
|
|
|
370
368
|
def _get_schema_from_runnable_and_arg_types(
|
|
371
369
|
runnable: Runnable,
|
|
372
370
|
name: str,
|
|
373
|
-
arg_types:
|
|
371
|
+
arg_types: dict[str, type] | None = None,
|
|
374
372
|
) -> type[BaseModel]:
|
|
375
373
|
"""Infer args_schema for tool."""
|
|
376
374
|
if arg_types is None:
|
|
@@ -389,11 +387,11 @@ def _get_schema_from_runnable_and_arg_types(
|
|
|
389
387
|
|
|
390
388
|
def convert_runnable_to_tool(
|
|
391
389
|
runnable: Runnable,
|
|
392
|
-
args_schema:
|
|
390
|
+
args_schema: type[BaseModel] | None = None,
|
|
393
391
|
*,
|
|
394
|
-
name:
|
|
395
|
-
description:
|
|
396
|
-
arg_types:
|
|
392
|
+
name: str | None = None,
|
|
393
|
+
description: str | None = None,
|
|
394
|
+
arg_types: dict[str, type] | None = None,
|
|
397
395
|
) -> BaseTool:
|
|
398
396
|
"""Convert a Runnable into a BaseTool.
|
|
399
397
|
|
|
@@ -421,12 +419,10 @@ def convert_runnable_to_tool(
|
|
|
421
419
|
description=description,
|
|
422
420
|
)
|
|
423
421
|
|
|
424
|
-
async def ainvoke_wrapper(
|
|
425
|
-
callbacks: Optional[Callbacks] = None, **kwargs: Any
|
|
426
|
-
) -> Any:
|
|
422
|
+
async def ainvoke_wrapper(callbacks: Callbacks | None = None, **kwargs: Any) -> Any:
|
|
427
423
|
return await runnable.ainvoke(kwargs, config={"callbacks": callbacks})
|
|
428
424
|
|
|
429
|
-
def invoke_wrapper(callbacks:
|
|
425
|
+
def invoke_wrapper(callbacks: Callbacks | None = None, **kwargs: Any) -> Any:
|
|
430
426
|
return runnable.invoke(kwargs, config={"callbacks": callbacks})
|
|
431
427
|
|
|
432
428
|
if (
|
langchain_core/tools/render.py
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
from functools import partial
|
|
6
|
-
from typing import TYPE_CHECKING, Literal
|
|
6
|
+
from typing import TYPE_CHECKING, Literal
|
|
7
7
|
|
|
8
8
|
from pydantic import BaseModel, Field
|
|
9
9
|
|
|
@@ -34,7 +34,7 @@ def _get_relevant_documents(
|
|
|
34
34
|
document_separator: str,
|
|
35
35
|
callbacks: Callbacks = None,
|
|
36
36
|
response_format: Literal["content", "content_and_artifact"] = "content",
|
|
37
|
-
) ->
|
|
37
|
+
) -> str | tuple[str, list[Document]]:
|
|
38
38
|
docs = retriever.invoke(query, config={"callbacks": callbacks})
|
|
39
39
|
content = document_separator.join(
|
|
40
40
|
format_document(doc, document_prompt) for doc in docs
|
|
@@ -52,7 +52,7 @@ async def _aget_relevant_documents(
|
|
|
52
52
|
document_separator: str,
|
|
53
53
|
callbacks: Callbacks = None,
|
|
54
54
|
response_format: Literal["content", "content_and_artifact"] = "content",
|
|
55
|
-
) ->
|
|
55
|
+
) -> str | tuple[str, list[Document]]:
|
|
56
56
|
docs = await retriever.ainvoke(query, config={"callbacks": callbacks})
|
|
57
57
|
content = document_separator.join(
|
|
58
58
|
[await aformat_document(doc, document_prompt) for doc in docs]
|
|
@@ -69,7 +69,7 @@ def create_retriever_tool(
|
|
|
69
69
|
name: str,
|
|
70
70
|
description: str,
|
|
71
71
|
*,
|
|
72
|
-
document_prompt:
|
|
72
|
+
document_prompt: BasePromptTemplate | None = None,
|
|
73
73
|
document_separator: str = "\n\n",
|
|
74
74
|
response_format: Literal["content", "content_and_artifact"] = "content",
|
|
75
75
|
) -> Tool:
|