langchain 1.0.0a14__py3-none-any.whl → 1.0.0rc1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of langchain might be problematic. Click here for more details.
- langchain/__init__.py +1 -1
- langchain/agents/__init__.py +7 -1
- langchain/agents/factory.py +74 -49
- langchain/agents/middleware/__init__.py +15 -6
- langchain/agents/middleware/context_editing.py +30 -2
- langchain/agents/middleware/human_in_the_loop.py +24 -20
- langchain/agents/middleware/model_call_limit.py +42 -9
- langchain/agents/middleware/model_fallback.py +36 -3
- langchain/agents/middleware/pii.py +7 -7
- langchain/agents/middleware/{planning.py → todo.py} +18 -5
- langchain/agents/middleware/tool_call_limit.py +89 -16
- langchain/agents/middleware/tool_emulator.py +2 -2
- langchain/agents/middleware/tool_retry.py +384 -0
- langchain/agents/middleware/types.py +111 -63
- langchain/agents/structured_output.py +29 -25
- langchain/chat_models/__init__.py +7 -1
- langchain/chat_models/base.py +98 -108
- langchain/embeddings/__init__.py +7 -1
- langchain/embeddings/base.py +1 -1
- langchain/messages/__init__.py +10 -1
- langchain/tools/__init__.py +9 -3
- langchain/tools/tool_node.py +288 -94
- langchain-1.0.0rc1.dist-info/METADATA +85 -0
- langchain-1.0.0rc1.dist-info/RECORD +30 -0
- langchain/agents/middleware/prompt_caching.py +0 -89
- langchain-1.0.0a14.dist-info/METADATA +0 -125
- langchain-1.0.0a14.dist-info/RECORD +0 -30
- {langchain-1.0.0a14.dist-info → langchain-1.0.0rc1.dist-info}/WHEEL +0 -0
- {langchain-1.0.0a14.dist-info → langchain-1.0.0rc1.dist-info}/licenses/LICENSE +0 -0
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
from collections.abc import Awaitable, Callable
|
|
6
|
-
from dataclasses import dataclass, field
|
|
6
|
+
from dataclasses import dataclass, field, replace
|
|
7
7
|
from inspect import iscoroutinefunction
|
|
8
8
|
from typing import (
|
|
9
9
|
TYPE_CHECKING,
|
|
@@ -26,11 +26,10 @@ from typing import TypeAlias
|
|
|
26
26
|
|
|
27
27
|
from langchain_core.messages import AIMessage, AnyMessage, BaseMessage, ToolMessage # noqa: TC002
|
|
28
28
|
from langgraph.channels.ephemeral_value import EphemeralValue
|
|
29
|
-
from langgraph.channels.untracked_value import UntrackedValue
|
|
30
29
|
from langgraph.graph.message import add_messages
|
|
31
30
|
from langgraph.types import Command # noqa: TC002
|
|
32
31
|
from langgraph.typing import ContextT
|
|
33
|
-
from typing_extensions import NotRequired, Required, TypedDict, TypeVar
|
|
32
|
+
from typing_extensions import NotRequired, Required, TypedDict, TypeVar, Unpack
|
|
34
33
|
|
|
35
34
|
if TYPE_CHECKING:
|
|
36
35
|
from langchain_core.language_models.chat_models import BaseChatModel
|
|
@@ -62,6 +61,18 @@ JumpTo = Literal["tools", "model", "end"]
|
|
|
62
61
|
ResponseT = TypeVar("ResponseT")
|
|
63
62
|
|
|
64
63
|
|
|
64
|
+
class _ModelRequestOverrides(TypedDict, total=False):
|
|
65
|
+
"""Possible overrides for ModelRequest.override() method."""
|
|
66
|
+
|
|
67
|
+
model: BaseChatModel
|
|
68
|
+
system_prompt: str | None
|
|
69
|
+
messages: list[AnyMessage]
|
|
70
|
+
tool_choice: Any | None
|
|
71
|
+
tools: list[BaseTool | dict]
|
|
72
|
+
response_format: ResponseFormat | None
|
|
73
|
+
model_settings: dict[str, Any]
|
|
74
|
+
|
|
75
|
+
|
|
65
76
|
@dataclass
|
|
66
77
|
class ModelRequest:
|
|
67
78
|
"""Model request information for the agent."""
|
|
@@ -76,6 +87,36 @@ class ModelRequest:
|
|
|
76
87
|
runtime: Runtime[ContextT] # type: ignore[valid-type]
|
|
77
88
|
model_settings: dict[str, Any] = field(default_factory=dict)
|
|
78
89
|
|
|
90
|
+
def override(self, **overrides: Unpack[_ModelRequestOverrides]) -> ModelRequest:
|
|
91
|
+
"""Replace the request with a new request with the given overrides.
|
|
92
|
+
|
|
93
|
+
Returns a new `ModelRequest` instance with the specified attributes replaced.
|
|
94
|
+
This follows an immutable pattern, leaving the original request unchanged.
|
|
95
|
+
|
|
96
|
+
Args:
|
|
97
|
+
**overrides: Keyword arguments for attributes to override. Supported keys:
|
|
98
|
+
- model: BaseChatModel instance
|
|
99
|
+
- system_prompt: Optional system prompt string
|
|
100
|
+
- messages: List of messages
|
|
101
|
+
- tool_choice: Tool choice configuration
|
|
102
|
+
- tools: List of available tools
|
|
103
|
+
- response_format: Response format specification
|
|
104
|
+
- model_settings: Additional model settings
|
|
105
|
+
|
|
106
|
+
Returns:
|
|
107
|
+
New ModelRequest instance with specified overrides applied.
|
|
108
|
+
|
|
109
|
+
Examples:
|
|
110
|
+
```python
|
|
111
|
+
# Create a new request with different model
|
|
112
|
+
new_request = request.override(model=different_model)
|
|
113
|
+
|
|
114
|
+
# Override multiple attributes
|
|
115
|
+
new_request = request.override(system_prompt="New instructions", tool_choice="auto")
|
|
116
|
+
```
|
|
117
|
+
"""
|
|
118
|
+
return replace(self, **overrides)
|
|
119
|
+
|
|
79
120
|
|
|
80
121
|
@dataclass
|
|
81
122
|
class ModelResponse:
|
|
@@ -129,8 +170,6 @@ class AgentState(TypedDict, Generic[ResponseT]):
|
|
|
129
170
|
messages: Required[Annotated[list[AnyMessage], add_messages]]
|
|
130
171
|
jump_to: NotRequired[Annotated[JumpTo | None, EphemeralValue, PrivateStateAttr]]
|
|
131
172
|
structured_response: NotRequired[Annotated[ResponseT, OmitFromInput]]
|
|
132
|
-
thread_model_call_count: NotRequired[Annotated[int, PrivateStateAttr]]
|
|
133
|
-
run_model_call_count: NotRequired[Annotated[int, UntrackedValue, PrivateStateAttr]]
|
|
134
173
|
|
|
135
174
|
|
|
136
175
|
class PublicAgentState(TypedDict, Generic[ResponseT]):
|
|
@@ -199,19 +238,19 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
199
238
|
) -> ModelCallResult:
|
|
200
239
|
"""Intercept and control model execution via handler callback.
|
|
201
240
|
|
|
202
|
-
The handler callback executes the model request and returns a ModelResponse
|
|
241
|
+
The handler callback executes the model request and returns a `ModelResponse`.
|
|
203
242
|
Middleware can call the handler multiple times for retry logic, skip calling
|
|
204
243
|
it to short-circuit, or modify the request/response. Multiple middleware
|
|
205
244
|
compose with first in list as outermost layer.
|
|
206
245
|
|
|
207
246
|
Args:
|
|
208
247
|
request: Model request to execute (includes state and runtime).
|
|
209
|
-
handler: Callback that executes the model request and returns
|
|
210
|
-
|
|
211
|
-
|
|
248
|
+
handler: Callback that executes the model request and returns
|
|
249
|
+
`ModelResponse`. Call this to execute the model. Can be called multiple
|
|
250
|
+
times for retry logic. Can skip calling it to short-circuit.
|
|
212
251
|
|
|
213
252
|
Returns:
|
|
214
|
-
ModelCallResult
|
|
253
|
+
`ModelCallResult`
|
|
215
254
|
|
|
216
255
|
Examples:
|
|
217
256
|
Retry on error:
|
|
@@ -282,16 +321,16 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
282
321
|
) -> ModelCallResult:
|
|
283
322
|
"""Intercept and control async model execution via handler callback.
|
|
284
323
|
|
|
285
|
-
The handler callback executes the model request and returns a ModelResponse
|
|
324
|
+
The handler callback executes the model request and returns a `ModelResponse`.
|
|
286
325
|
Middleware can call the handler multiple times for retry logic, skip calling
|
|
287
326
|
it to short-circuit, or modify the request/response. Multiple middleware
|
|
288
327
|
compose with first in list as outermost layer.
|
|
289
328
|
|
|
290
329
|
Args:
|
|
291
330
|
request: Model request to execute (includes state and runtime).
|
|
292
|
-
handler: Async callback that executes the model request and returns
|
|
293
|
-
|
|
294
|
-
|
|
331
|
+
handler: Async callback that executes the model request and returns
|
|
332
|
+
`ModelResponse`. Call this to execute the model. Can be called multiple
|
|
333
|
+
times for retry logic. Can skip calling it to short-circuit.
|
|
295
334
|
|
|
296
335
|
Returns:
|
|
297
336
|
ModelCallResult
|
|
@@ -336,15 +375,15 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
336
375
|
"""Intercept tool execution for retries, monitoring, or modification.
|
|
337
376
|
|
|
338
377
|
Multiple middleware compose automatically (first defined = outermost).
|
|
339
|
-
Exceptions propagate unless handle_tool_errors is configured on ToolNode
|
|
378
|
+
Exceptions propagate unless `handle_tool_errors` is configured on `ToolNode`.
|
|
340
379
|
|
|
341
380
|
Args:
|
|
342
|
-
request: Tool call request with call dict
|
|
343
|
-
Access state via request.state and runtime via request.runtime
|
|
381
|
+
request: Tool call request with call `dict`, `BaseTool`, state, and runtime.
|
|
382
|
+
Access state via `request.state` and runtime via `request.runtime`.
|
|
344
383
|
handler: Callable to execute the tool (can be called multiple times).
|
|
345
384
|
|
|
346
385
|
Returns:
|
|
347
|
-
ToolMessage or Command (the final result).
|
|
386
|
+
`ToolMessage` or `Command` (the final result).
|
|
348
387
|
|
|
349
388
|
The handler callable can be invoked multiple times for retry logic.
|
|
350
389
|
Each call to handler is independent and stateless.
|
|
@@ -352,12 +391,15 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
352
391
|
Examples:
|
|
353
392
|
Modify request before execution:
|
|
354
393
|
|
|
394
|
+
```python
|
|
355
395
|
def wrap_tool_call(self, request, handler):
|
|
356
396
|
request.tool_call["args"]["value"] *= 2
|
|
357
397
|
return handler(request)
|
|
398
|
+
```
|
|
358
399
|
|
|
359
400
|
Retry on error (call handler multiple times):
|
|
360
401
|
|
|
402
|
+
```python
|
|
361
403
|
def wrap_tool_call(self, request, handler):
|
|
362
404
|
for attempt in range(3):
|
|
363
405
|
try:
|
|
@@ -368,9 +410,11 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
368
410
|
if attempt == 2:
|
|
369
411
|
raise
|
|
370
412
|
return result
|
|
413
|
+
```
|
|
371
414
|
|
|
372
415
|
Conditional retry based on response:
|
|
373
416
|
|
|
417
|
+
```python
|
|
374
418
|
def wrap_tool_call(self, request, handler):
|
|
375
419
|
for attempt in range(3):
|
|
376
420
|
result = handler(request)
|
|
@@ -379,6 +423,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
379
423
|
if attempt < 2:
|
|
380
424
|
continue
|
|
381
425
|
return result
|
|
426
|
+
```
|
|
382
427
|
"""
|
|
383
428
|
msg = (
|
|
384
429
|
"Synchronous implementation of wrap_tool_call is not available. "
|
|
@@ -399,20 +444,20 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
399
444
|
) -> ToolMessage | Command:
|
|
400
445
|
"""Intercept and control async tool execution via handler callback.
|
|
401
446
|
|
|
402
|
-
The handler callback executes the tool call and returns a ToolMessage or
|
|
403
|
-
Middleware can call the handler multiple times for retry logic, skip
|
|
404
|
-
it to short-circuit, or modify the request/response. Multiple middleware
|
|
447
|
+
The handler callback executes the tool call and returns a `ToolMessage` or
|
|
448
|
+
`Command`. Middleware can call the handler multiple times for retry logic, skip
|
|
449
|
+
calling it to short-circuit, or modify the request/response. Multiple middleware
|
|
405
450
|
compose with first in list as outermost layer.
|
|
406
451
|
|
|
407
452
|
Args:
|
|
408
|
-
request: Tool call request with call dict
|
|
409
|
-
Access state via request.state and runtime via request.runtime
|
|
410
|
-
handler: Async callable to execute the tool and returns ToolMessage or
|
|
411
|
-
|
|
412
|
-
|
|
453
|
+
request: Tool call request with call `dict`, `BaseTool`, state, and runtime.
|
|
454
|
+
Access state via `request.state` and runtime via `request.runtime`.
|
|
455
|
+
handler: Async callable to execute the tool and returns `ToolMessage` or
|
|
456
|
+
`Command`. Call this to execute the tool. Can be called multiple times
|
|
457
|
+
for retry logic. Can skip calling it to short-circuit.
|
|
413
458
|
|
|
414
459
|
Returns:
|
|
415
|
-
ToolMessage or Command (the final result).
|
|
460
|
+
`ToolMessage` or `Command` (the final result).
|
|
416
461
|
|
|
417
462
|
The handler callable can be invoked multiple times for retry logic.
|
|
418
463
|
Each call to handler is independent and stateless.
|
|
@@ -432,13 +477,14 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
432
477
|
return result
|
|
433
478
|
```
|
|
434
479
|
|
|
435
|
-
|
|
480
|
+
```python
|
|
436
481
|
async def awrap_tool_call(self, request, handler):
|
|
437
482
|
if cached := await get_cache_async(request):
|
|
438
483
|
return ToolMessage(content=cached, tool_call_id=request.tool_call["id"])
|
|
439
484
|
result = await handler(request)
|
|
440
485
|
await save_cache_async(request, result)
|
|
441
486
|
return result
|
|
487
|
+
```
|
|
442
488
|
"""
|
|
443
489
|
msg = (
|
|
444
490
|
"Asynchronous implementation of awrap_tool_call is not available. "
|
|
@@ -454,7 +500,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
454
500
|
|
|
455
501
|
|
|
456
502
|
class _CallableWithStateAndRuntime(Protocol[StateT_contra, ContextT]):
|
|
457
|
-
"""Callable with AgentState and Runtime as arguments."""
|
|
503
|
+
"""Callable with `AgentState` and `Runtime` as arguments."""
|
|
458
504
|
|
|
459
505
|
def __call__(
|
|
460
506
|
self, state: StateT_contra, runtime: Runtime[ContextT]
|
|
@@ -464,7 +510,7 @@ class _CallableWithStateAndRuntime(Protocol[StateT_contra, ContextT]):
|
|
|
464
510
|
|
|
465
511
|
|
|
466
512
|
class _CallableReturningPromptString(Protocol[StateT_contra, ContextT]): # type: ignore[misc]
|
|
467
|
-
"""Callable that returns a prompt string given ModelRequest (contains state and runtime)."""
|
|
513
|
+
"""Callable that returns a prompt string given `ModelRequest` (contains state and runtime)."""
|
|
468
514
|
|
|
469
515
|
def __call__(self, request: ModelRequest) -> str | Awaitable[str]:
|
|
470
516
|
"""Generate a system prompt string based on the request."""
|
|
@@ -474,7 +520,8 @@ class _CallableReturningPromptString(Protocol[StateT_contra, ContextT]): # type
|
|
|
474
520
|
class _CallableReturningModelResponse(Protocol[StateT_contra, ContextT]): # type: ignore[misc]
|
|
475
521
|
"""Callable for model call interception with handler callback.
|
|
476
522
|
|
|
477
|
-
Receives handler callback to execute model and returns ModelResponse or
|
|
523
|
+
Receives handler callback to execute model and returns `ModelResponse` or
|
|
524
|
+
`AIMessage`.
|
|
478
525
|
"""
|
|
479
526
|
|
|
480
527
|
def __call__(
|
|
@@ -489,7 +536,8 @@ class _CallableReturningModelResponse(Protocol[StateT_contra, ContextT]): # typ
|
|
|
489
536
|
class _CallableReturningToolResponse(Protocol):
|
|
490
537
|
"""Callable for tool call interception with handler callback.
|
|
491
538
|
|
|
492
|
-
Receives handler callback to execute tool and returns final ToolMessage or
|
|
539
|
+
Receives handler callback to execute tool and returns final `ToolMessage` or
|
|
540
|
+
`Command`.
|
|
493
541
|
"""
|
|
494
542
|
|
|
495
543
|
def __call__(
|
|
@@ -582,22 +630,22 @@ def before_model(
|
|
|
582
630
|
Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]
|
|
583
631
|
| AgentMiddleware[StateT, ContextT]
|
|
584
632
|
):
|
|
585
|
-
"""Decorator used to dynamically create a middleware with the before_model hook.
|
|
633
|
+
"""Decorator used to dynamically create a middleware with the `before_model` hook.
|
|
586
634
|
|
|
587
635
|
Args:
|
|
588
636
|
func: The function to be decorated. Must accept:
|
|
589
637
|
`state: StateT, runtime: Runtime[ContextT]` - State and runtime context
|
|
590
638
|
state_schema: Optional custom state schema type. If not provided, uses the default
|
|
591
|
-
AgentState schema.
|
|
639
|
+
`AgentState` schema.
|
|
592
640
|
tools: Optional list of additional tools to register with this middleware.
|
|
593
641
|
can_jump_to: Optional list of valid jump destinations for conditional edges.
|
|
594
|
-
Valid values are: "tools"
|
|
642
|
+
Valid values are: `"tools"`, `"model"`, `"end"`
|
|
595
643
|
name: Optional name for the generated middleware class. If not provided,
|
|
596
644
|
uses the decorated function's name.
|
|
597
645
|
|
|
598
646
|
Returns:
|
|
599
|
-
Either an AgentMiddleware instance (if func is provided directly) or a
|
|
600
|
-
that can be applied to a function it is wrapping.
|
|
647
|
+
Either an `AgentMiddleware` instance (if func is provided directly) or a
|
|
648
|
+
decorator function that can be applied to a function it is wrapping.
|
|
601
649
|
|
|
602
650
|
The decorated function should return:
|
|
603
651
|
- `dict[str, Any]` - State updates to merge into the agent state
|
|
@@ -724,22 +772,22 @@ def after_model(
|
|
|
724
772
|
Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]
|
|
725
773
|
| AgentMiddleware[StateT, ContextT]
|
|
726
774
|
):
|
|
727
|
-
"""Decorator used to dynamically create a middleware with the after_model hook.
|
|
775
|
+
"""Decorator used to dynamically create a middleware with the `after_model` hook.
|
|
728
776
|
|
|
729
777
|
Args:
|
|
730
778
|
func: The function to be decorated. Must accept:
|
|
731
779
|
`state: StateT, runtime: Runtime[ContextT]` - State and runtime context
|
|
732
|
-
state_schema: Optional custom state schema type. If not provided, uses the
|
|
733
|
-
AgentState schema.
|
|
780
|
+
state_schema: Optional custom state schema type. If not provided, uses the
|
|
781
|
+
default `AgentState` schema.
|
|
734
782
|
tools: Optional list of additional tools to register with this middleware.
|
|
735
783
|
can_jump_to: Optional list of valid jump destinations for conditional edges.
|
|
736
|
-
Valid values are: "tools"
|
|
784
|
+
Valid values are: `"tools"`, `"model"`, `"end"`
|
|
737
785
|
name: Optional name for the generated middleware class. If not provided,
|
|
738
786
|
uses the decorated function's name.
|
|
739
787
|
|
|
740
788
|
Returns:
|
|
741
|
-
Either an AgentMiddleware instance (if func is provided) or a decorator
|
|
742
|
-
that can be applied to a function.
|
|
789
|
+
Either an `AgentMiddleware` instance (if func is provided) or a decorator
|
|
790
|
+
function that can be applied to a function.
|
|
743
791
|
|
|
744
792
|
The decorated function should return:
|
|
745
793
|
- `dict[str, Any]` - State updates to merge into the agent state
|
|
@@ -855,22 +903,22 @@ def before_agent(
|
|
|
855
903
|
Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]
|
|
856
904
|
| AgentMiddleware[StateT, ContextT]
|
|
857
905
|
):
|
|
858
|
-
"""Decorator used to dynamically create a middleware with the before_agent hook.
|
|
906
|
+
"""Decorator used to dynamically create a middleware with the `before_agent` hook.
|
|
859
907
|
|
|
860
908
|
Args:
|
|
861
909
|
func: The function to be decorated. Must accept:
|
|
862
910
|
`state: StateT, runtime: Runtime[ContextT]` - State and runtime context
|
|
863
|
-
state_schema: Optional custom state schema type. If not provided, uses the
|
|
864
|
-
AgentState schema.
|
|
911
|
+
state_schema: Optional custom state schema type. If not provided, uses the
|
|
912
|
+
default `AgentState` schema.
|
|
865
913
|
tools: Optional list of additional tools to register with this middleware.
|
|
866
914
|
can_jump_to: Optional list of valid jump destinations for conditional edges.
|
|
867
|
-
Valid values are: "tools"
|
|
915
|
+
Valid values are: `"tools"`, `"model"`, `"end"`
|
|
868
916
|
name: Optional name for the generated middleware class. If not provided,
|
|
869
917
|
uses the decorated function's name.
|
|
870
918
|
|
|
871
919
|
Returns:
|
|
872
|
-
Either an AgentMiddleware instance (if func is provided directly) or a
|
|
873
|
-
that can be applied to a function it is wrapping.
|
|
920
|
+
Either an `AgentMiddleware` instance (if func is provided directly) or a
|
|
921
|
+
decorator function that can be applied to a function it is wrapping.
|
|
874
922
|
|
|
875
923
|
The decorated function should return:
|
|
876
924
|
- `dict[str, Any]` - State updates to merge into the agent state
|
|
@@ -997,22 +1045,22 @@ def after_agent(
|
|
|
997
1045
|
Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]
|
|
998
1046
|
| AgentMiddleware[StateT, ContextT]
|
|
999
1047
|
):
|
|
1000
|
-
"""Decorator used to dynamically create a middleware with the after_agent hook.
|
|
1048
|
+
"""Decorator used to dynamically create a middleware with the `after_agent` hook.
|
|
1001
1049
|
|
|
1002
1050
|
Args:
|
|
1003
1051
|
func: The function to be decorated. Must accept:
|
|
1004
1052
|
`state: StateT, runtime: Runtime[ContextT]` - State and runtime context
|
|
1005
|
-
state_schema: Optional custom state schema type. If not provided, uses the
|
|
1006
|
-
AgentState schema.
|
|
1053
|
+
state_schema: Optional custom state schema type. If not provided, uses the
|
|
1054
|
+
default `AgentState` schema.
|
|
1007
1055
|
tools: Optional list of additional tools to register with this middleware.
|
|
1008
1056
|
can_jump_to: Optional list of valid jump destinations for conditional edges.
|
|
1009
|
-
Valid values are: "tools"
|
|
1057
|
+
Valid values are: `"tools"`, `"model"`, `"end"`
|
|
1010
1058
|
name: Optional name for the generated middleware class. If not provided,
|
|
1011
1059
|
uses the decorated function's name.
|
|
1012
1060
|
|
|
1013
1061
|
Returns:
|
|
1014
|
-
Either an AgentMiddleware instance (if func is provided) or a decorator
|
|
1015
|
-
that can be applied to a function.
|
|
1062
|
+
Either an `AgentMiddleware` instance (if func is provided) or a decorator
|
|
1063
|
+
function that can be applied to a function.
|
|
1016
1064
|
|
|
1017
1065
|
The decorated function should return:
|
|
1018
1066
|
- `dict[str, Any]` - State updates to merge into the agent state
|
|
@@ -1261,21 +1309,21 @@ def wrap_model_call(
|
|
|
1261
1309
|
]
|
|
1262
1310
|
| AgentMiddleware[StateT, ContextT]
|
|
1263
1311
|
):
|
|
1264
|
-
"""Create middleware with wrap_model_call hook from a function.
|
|
1312
|
+
"""Create middleware with `wrap_model_call` hook from a function.
|
|
1265
1313
|
|
|
1266
1314
|
Converts a function with handler callback into middleware that can intercept
|
|
1267
1315
|
model calls, implement retry logic, handle errors, and rewrite responses.
|
|
1268
1316
|
|
|
1269
1317
|
Args:
|
|
1270
1318
|
func: Function accepting (request, handler) that calls handler(request)
|
|
1271
|
-
to execute the model and returns ModelResponse or AIMessage
|
|
1319
|
+
to execute the model and returns `ModelResponse` or `AIMessage`.
|
|
1272
1320
|
Request contains state and runtime.
|
|
1273
|
-
state_schema: Custom state schema. Defaults to AgentState
|
|
1321
|
+
state_schema: Custom state schema. Defaults to `AgentState`.
|
|
1274
1322
|
tools: Additional tools to register with this middleware.
|
|
1275
1323
|
name: Middleware class name. Defaults to function name.
|
|
1276
1324
|
|
|
1277
1325
|
Returns:
|
|
1278
|
-
AgentMiddleware instance if func provided, otherwise a decorator.
|
|
1326
|
+
`AgentMiddleware` instance if func provided, otherwise a decorator.
|
|
1279
1327
|
|
|
1280
1328
|
Examples:
|
|
1281
1329
|
Basic retry logic:
|
|
@@ -1409,20 +1457,20 @@ def wrap_tool_call(
|
|
|
1409
1457
|
]
|
|
1410
1458
|
| AgentMiddleware
|
|
1411
1459
|
):
|
|
1412
|
-
"""Create middleware with wrap_tool_call hook from a function.
|
|
1460
|
+
"""Create middleware with `wrap_tool_call` hook from a function.
|
|
1413
1461
|
|
|
1414
1462
|
Converts a function with handler callback into middleware that can intercept
|
|
1415
1463
|
tool calls, implement retry logic, monitor execution, and modify responses.
|
|
1416
1464
|
|
|
1417
1465
|
Args:
|
|
1418
1466
|
func: Function accepting (request, handler) that calls
|
|
1419
|
-
handler(request) to execute the tool and returns final ToolMessage or
|
|
1420
|
-
Can be sync or async.
|
|
1467
|
+
handler(request) to execute the tool and returns final `ToolMessage` or
|
|
1468
|
+
`Command`. Can be sync or async.
|
|
1421
1469
|
tools: Additional tools to register with this middleware.
|
|
1422
1470
|
name: Middleware class name. Defaults to function name.
|
|
1423
1471
|
|
|
1424
1472
|
Returns:
|
|
1425
|
-
AgentMiddleware instance if func provided, otherwise a decorator.
|
|
1473
|
+
`AgentMiddleware` instance if func provided, otherwise a decorator.
|
|
1426
1474
|
|
|
1427
1475
|
Examples:
|
|
1428
1476
|
Retry logic:
|
|
@@ -39,7 +39,7 @@ class MultipleStructuredOutputsError(StructuredOutputError):
|
|
|
39
39
|
"""Raised when model returns multiple structured output tool calls when only one is expected."""
|
|
40
40
|
|
|
41
41
|
def __init__(self, tool_names: list[str]) -> None:
|
|
42
|
-
"""Initialize MultipleStructuredOutputsError
|
|
42
|
+
"""Initialize `MultipleStructuredOutputsError`.
|
|
43
43
|
|
|
44
44
|
Args:
|
|
45
45
|
tool_names: The names of the tools called for structured output.
|
|
@@ -56,7 +56,7 @@ class StructuredOutputValidationError(StructuredOutputError):
|
|
|
56
56
|
"""Raised when structured output tool call arguments fail to parse according to the schema."""
|
|
57
57
|
|
|
58
58
|
def __init__(self, tool_name: str, source: Exception) -> None:
|
|
59
|
-
"""Initialize StructuredOutputValidationError
|
|
59
|
+
"""Initialize `StructuredOutputValidationError`.
|
|
60
60
|
|
|
61
61
|
Args:
|
|
62
62
|
tool_name: The name of the tool that failed.
|
|
@@ -73,8 +73,9 @@ def _parse_with_schema(
|
|
|
73
73
|
"""Parse data using for any supported schema type.
|
|
74
74
|
|
|
75
75
|
Args:
|
|
76
|
-
schema: The schema type (Pydantic model, dataclass
|
|
77
|
-
schema_kind: One of "pydantic"
|
|
76
|
+
schema: The schema type (Pydantic model, `dataclass`, or `TypedDict`)
|
|
77
|
+
schema_kind: One of `"pydantic"`, `"dataclass"`, `"typeddict"`, or
|
|
78
|
+
`"json_schema"`
|
|
78
79
|
data: The data to parse
|
|
79
80
|
|
|
80
81
|
Returns:
|
|
@@ -99,13 +100,14 @@ class _SchemaSpec(Generic[SchemaT]):
|
|
|
99
100
|
"""Describes a structured output schema."""
|
|
100
101
|
|
|
101
102
|
schema: type[SchemaT]
|
|
102
|
-
"""The schema for the response, can be a Pydantic model, dataclass
|
|
103
|
+
"""The schema for the response, can be a Pydantic model, `dataclass`, `TypedDict`,
|
|
103
104
|
or JSON schema dict."""
|
|
104
105
|
|
|
105
106
|
name: str
|
|
106
107
|
"""Name of the schema, used for tool calling.
|
|
107
108
|
|
|
108
|
-
If not provided, the name will be the model name or "response_format" if it's a
|
|
109
|
+
If not provided, the name will be the model name or `"response_format"` if it's a
|
|
110
|
+
JSON schema.
|
|
109
111
|
"""
|
|
110
112
|
|
|
111
113
|
description: str
|
|
@@ -186,14 +188,15 @@ class ToolStrategy(Generic[SchemaT]):
|
|
|
186
188
|
handle_errors: (
|
|
187
189
|
bool | str | type[Exception] | tuple[type[Exception], ...] | Callable[[Exception], str]
|
|
188
190
|
)
|
|
189
|
-
"""Error handling strategy for structured output via ToolStrategy
|
|
190
|
-
|
|
191
|
-
- True
|
|
192
|
-
- str
|
|
193
|
-
- type[Exception]
|
|
194
|
-
- tuple[type[Exception], ...]
|
|
195
|
-
|
|
196
|
-
-
|
|
191
|
+
"""Error handling strategy for structured output via `ToolStrategy`.
|
|
192
|
+
|
|
193
|
+
- `True`: Catch all errors with default error template
|
|
194
|
+
- `str`: Catch all errors with this custom message
|
|
195
|
+
- `type[Exception]`: Only catch this exception type with default message
|
|
196
|
+
- `tuple[type[Exception], ...]`: Only catch these exception types with default
|
|
197
|
+
message
|
|
198
|
+
- `Callable[[Exception], str]`: Custom function that returns error message
|
|
199
|
+
- `False`: No retry, let exceptions propagate
|
|
197
200
|
"""
|
|
198
201
|
|
|
199
202
|
def __init__(
|
|
@@ -207,9 +210,10 @@ class ToolStrategy(Generic[SchemaT]):
|
|
|
207
210
|
| tuple[type[Exception], ...]
|
|
208
211
|
| Callable[[Exception], str] = True,
|
|
209
212
|
) -> None:
|
|
210
|
-
"""Initialize ToolStrategy
|
|
213
|
+
"""Initialize `ToolStrategy`.
|
|
211
214
|
|
|
212
|
-
Initialize ToolStrategy with schemas, tool message content, and error handling
|
|
215
|
+
Initialize `ToolStrategy` with schemas, tool message content, and error handling
|
|
216
|
+
strategy.
|
|
213
217
|
"""
|
|
214
218
|
self.schema = schema
|
|
215
219
|
self.tool_message_content = tool_message_content
|
|
@@ -285,13 +289,13 @@ class OutputToolBinding(Generic[SchemaT]):
|
|
|
285
289
|
|
|
286
290
|
@classmethod
|
|
287
291
|
def from_schema_spec(cls, schema_spec: _SchemaSpec[SchemaT]) -> Self:
|
|
288
|
-
"""Create an OutputToolBinding instance from a SchemaSpec
|
|
292
|
+
"""Create an `OutputToolBinding` instance from a `SchemaSpec`.
|
|
289
293
|
|
|
290
294
|
Args:
|
|
291
|
-
schema_spec: The SchemaSpec to convert
|
|
295
|
+
schema_spec: The `SchemaSpec` to convert
|
|
292
296
|
|
|
293
297
|
Returns:
|
|
294
|
-
An OutputToolBinding instance with the appropriate tool created
|
|
298
|
+
An `OutputToolBinding` instance with the appropriate tool created
|
|
295
299
|
"""
|
|
296
300
|
return cls(
|
|
297
301
|
schema=schema_spec.schema,
|
|
@@ -329,20 +333,20 @@ class ProviderStrategyBinding(Generic[SchemaT]):
|
|
|
329
333
|
|
|
330
334
|
schema: type[SchemaT]
|
|
331
335
|
"""The original schema provided for structured output
|
|
332
|
-
(Pydantic model, dataclass
|
|
336
|
+
(Pydantic model, `dataclass`, `TypedDict`, or JSON schema dict)."""
|
|
333
337
|
|
|
334
338
|
schema_kind: SchemaKind
|
|
335
339
|
"""Classification of the schema type for proper response construction."""
|
|
336
340
|
|
|
337
341
|
@classmethod
|
|
338
342
|
def from_schema_spec(cls, schema_spec: _SchemaSpec[SchemaT]) -> Self:
|
|
339
|
-
"""Create a ProviderStrategyBinding instance from a SchemaSpec
|
|
343
|
+
"""Create a `ProviderStrategyBinding` instance from a `SchemaSpec`.
|
|
340
344
|
|
|
341
345
|
Args:
|
|
342
|
-
schema_spec: The SchemaSpec to convert
|
|
346
|
+
schema_spec: The `SchemaSpec` to convert
|
|
343
347
|
|
|
344
348
|
Returns:
|
|
345
|
-
A ProviderStrategyBinding instance for parsing native structured output
|
|
349
|
+
A `ProviderStrategyBinding` instance for parsing native structured output
|
|
346
350
|
"""
|
|
347
351
|
return cls(
|
|
348
352
|
schema=schema_spec.schema,
|
|
@@ -350,10 +354,10 @@ class ProviderStrategyBinding(Generic[SchemaT]):
|
|
|
350
354
|
)
|
|
351
355
|
|
|
352
356
|
def parse(self, response: AIMessage) -> SchemaT:
|
|
353
|
-
"""Parse AIMessage content according to the schema.
|
|
357
|
+
"""Parse `AIMessage` content according to the schema.
|
|
354
358
|
|
|
355
359
|
Args:
|
|
356
|
-
response: The
|
|
360
|
+
response: The `AIMessage` containing the structured output
|
|
357
361
|
|
|
358
362
|
Returns:
|
|
359
363
|
The parsed response according to the schema
|
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Entrypoint to using [chat models](https://docs.langchain.com/oss/python/langchain/models) in LangChain.
|
|
2
|
+
|
|
3
|
+
!!! warning "Reference docs"
|
|
4
|
+
This page contains **reference documentation** for chat models. See
|
|
5
|
+
[the docs](https://docs.langchain.com/oss/python/langchain/models) for conceptual
|
|
6
|
+
guides, tutorials, and examples on using chat models.
|
|
7
|
+
""" # noqa: E501
|
|
2
8
|
|
|
3
9
|
from langchain_core.language_models import BaseChatModel
|
|
4
10
|
|