langchain 1.0.0a15__py3-none-any.whl → 1.0.0rc2__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 +57 -32
- langchain/agents/middleware/__init__.py +9 -1
- langchain/agents/middleware/context_editing.py +1 -1
- langchain/agents/middleware/human_in_the_loop.py +11 -7
- langchain/agents/middleware/model_call_limit.py +4 -5
- langchain/agents/middleware/model_fallback.py +0 -2
- langchain/agents/middleware/pii.py +7 -7
- langchain/agents/middleware/tool_call_limit.py +1 -1
- langchain/agents/middleware/tool_emulator.py +2 -2
- langchain/agents/middleware/tool_retry.py +384 -0
- langchain/agents/middleware/types.py +67 -58
- 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 -2
- langchain/tools/tool_node.py +257 -94
- {langchain-1.0.0a15.dist-info → langchain-1.0.0rc2.dist-info}/METADATA +2 -2
- langchain-1.0.0rc2.dist-info/RECORD +30 -0
- langchain-1.0.0a15.dist-info/RECORD +0 -29
- {langchain-1.0.0a15.dist-info → langchain-1.0.0rc2.dist-info}/WHEEL +0 -0
- {langchain-1.0.0a15.dist-info → langchain-1.0.0rc2.dist-info}/licenses/LICENSE +0 -0
|
@@ -238,19 +238,19 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
238
238
|
) -> ModelCallResult:
|
|
239
239
|
"""Intercept and control model execution via handler callback.
|
|
240
240
|
|
|
241
|
-
The handler callback executes the model request and returns a ModelResponse
|
|
241
|
+
The handler callback executes the model request and returns a `ModelResponse`.
|
|
242
242
|
Middleware can call the handler multiple times for retry logic, skip calling
|
|
243
243
|
it to short-circuit, or modify the request/response. Multiple middleware
|
|
244
244
|
compose with first in list as outermost layer.
|
|
245
245
|
|
|
246
246
|
Args:
|
|
247
247
|
request: Model request to execute (includes state and runtime).
|
|
248
|
-
handler: Callback that executes the model request and returns
|
|
249
|
-
|
|
250
|
-
|
|
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.
|
|
251
251
|
|
|
252
252
|
Returns:
|
|
253
|
-
ModelCallResult
|
|
253
|
+
`ModelCallResult`
|
|
254
254
|
|
|
255
255
|
Examples:
|
|
256
256
|
Retry on error:
|
|
@@ -321,16 +321,16 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
321
321
|
) -> ModelCallResult:
|
|
322
322
|
"""Intercept and control async model execution via handler callback.
|
|
323
323
|
|
|
324
|
-
The handler callback executes the model request and returns a ModelResponse
|
|
324
|
+
The handler callback executes the model request and returns a `ModelResponse`.
|
|
325
325
|
Middleware can call the handler multiple times for retry logic, skip calling
|
|
326
326
|
it to short-circuit, or modify the request/response. Multiple middleware
|
|
327
327
|
compose with first in list as outermost layer.
|
|
328
328
|
|
|
329
329
|
Args:
|
|
330
330
|
request: Model request to execute (includes state and runtime).
|
|
331
|
-
handler: Async callback that executes the model request and returns
|
|
332
|
-
|
|
333
|
-
|
|
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.
|
|
334
334
|
|
|
335
335
|
Returns:
|
|
336
336
|
ModelCallResult
|
|
@@ -375,15 +375,15 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
375
375
|
"""Intercept tool execution for retries, monitoring, or modification.
|
|
376
376
|
|
|
377
377
|
Multiple middleware compose automatically (first defined = outermost).
|
|
378
|
-
Exceptions propagate unless handle_tool_errors is configured on ToolNode
|
|
378
|
+
Exceptions propagate unless `handle_tool_errors` is configured on `ToolNode`.
|
|
379
379
|
|
|
380
380
|
Args:
|
|
381
|
-
request: Tool call request with call dict
|
|
382
|
-
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`.
|
|
383
383
|
handler: Callable to execute the tool (can be called multiple times).
|
|
384
384
|
|
|
385
385
|
Returns:
|
|
386
|
-
ToolMessage or Command (the final result).
|
|
386
|
+
`ToolMessage` or `Command` (the final result).
|
|
387
387
|
|
|
388
388
|
The handler callable can be invoked multiple times for retry logic.
|
|
389
389
|
Each call to handler is independent and stateless.
|
|
@@ -391,12 +391,15 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
391
391
|
Examples:
|
|
392
392
|
Modify request before execution:
|
|
393
393
|
|
|
394
|
+
```python
|
|
394
395
|
def wrap_tool_call(self, request, handler):
|
|
395
396
|
request.tool_call["args"]["value"] *= 2
|
|
396
397
|
return handler(request)
|
|
398
|
+
```
|
|
397
399
|
|
|
398
400
|
Retry on error (call handler multiple times):
|
|
399
401
|
|
|
402
|
+
```python
|
|
400
403
|
def wrap_tool_call(self, request, handler):
|
|
401
404
|
for attempt in range(3):
|
|
402
405
|
try:
|
|
@@ -407,9 +410,11 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
407
410
|
if attempt == 2:
|
|
408
411
|
raise
|
|
409
412
|
return result
|
|
413
|
+
```
|
|
410
414
|
|
|
411
415
|
Conditional retry based on response:
|
|
412
416
|
|
|
417
|
+
```python
|
|
413
418
|
def wrap_tool_call(self, request, handler):
|
|
414
419
|
for attempt in range(3):
|
|
415
420
|
result = handler(request)
|
|
@@ -418,6 +423,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
418
423
|
if attempt < 2:
|
|
419
424
|
continue
|
|
420
425
|
return result
|
|
426
|
+
```
|
|
421
427
|
"""
|
|
422
428
|
msg = (
|
|
423
429
|
"Synchronous implementation of wrap_tool_call is not available. "
|
|
@@ -438,20 +444,20 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
438
444
|
) -> ToolMessage | Command:
|
|
439
445
|
"""Intercept and control async tool execution via handler callback.
|
|
440
446
|
|
|
441
|
-
The handler callback executes the tool call and returns a ToolMessage or
|
|
442
|
-
Middleware can call the handler multiple times for retry logic, skip
|
|
443
|
-
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
|
|
444
450
|
compose with first in list as outermost layer.
|
|
445
451
|
|
|
446
452
|
Args:
|
|
447
|
-
request: Tool call request with call dict
|
|
448
|
-
Access state via request.state and runtime via request.runtime
|
|
449
|
-
handler: Async callable to execute the tool and returns ToolMessage or
|
|
450
|
-
|
|
451
|
-
|
|
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.
|
|
452
458
|
|
|
453
459
|
Returns:
|
|
454
|
-
ToolMessage or Command (the final result).
|
|
460
|
+
`ToolMessage` or `Command` (the final result).
|
|
455
461
|
|
|
456
462
|
The handler callable can be invoked multiple times for retry logic.
|
|
457
463
|
Each call to handler is independent and stateless.
|
|
@@ -471,13 +477,14 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
471
477
|
return result
|
|
472
478
|
```
|
|
473
479
|
|
|
474
|
-
|
|
480
|
+
```python
|
|
475
481
|
async def awrap_tool_call(self, request, handler):
|
|
476
482
|
if cached := await get_cache_async(request):
|
|
477
483
|
return ToolMessage(content=cached, tool_call_id=request.tool_call["id"])
|
|
478
484
|
result = await handler(request)
|
|
479
485
|
await save_cache_async(request, result)
|
|
480
486
|
return result
|
|
487
|
+
```
|
|
481
488
|
"""
|
|
482
489
|
msg = (
|
|
483
490
|
"Asynchronous implementation of awrap_tool_call is not available. "
|
|
@@ -493,7 +500,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):
|
|
|
493
500
|
|
|
494
501
|
|
|
495
502
|
class _CallableWithStateAndRuntime(Protocol[StateT_contra, ContextT]):
|
|
496
|
-
"""Callable with AgentState and Runtime as arguments."""
|
|
503
|
+
"""Callable with `AgentState` and `Runtime` as arguments."""
|
|
497
504
|
|
|
498
505
|
def __call__(
|
|
499
506
|
self, state: StateT_contra, runtime: Runtime[ContextT]
|
|
@@ -503,7 +510,7 @@ class _CallableWithStateAndRuntime(Protocol[StateT_contra, ContextT]):
|
|
|
503
510
|
|
|
504
511
|
|
|
505
512
|
class _CallableReturningPromptString(Protocol[StateT_contra, ContextT]): # type: ignore[misc]
|
|
506
|
-
"""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)."""
|
|
507
514
|
|
|
508
515
|
def __call__(self, request: ModelRequest) -> str | Awaitable[str]:
|
|
509
516
|
"""Generate a system prompt string based on the request."""
|
|
@@ -513,7 +520,8 @@ class _CallableReturningPromptString(Protocol[StateT_contra, ContextT]): # type
|
|
|
513
520
|
class _CallableReturningModelResponse(Protocol[StateT_contra, ContextT]): # type: ignore[misc]
|
|
514
521
|
"""Callable for model call interception with handler callback.
|
|
515
522
|
|
|
516
|
-
Receives handler callback to execute model and returns ModelResponse or
|
|
523
|
+
Receives handler callback to execute model and returns `ModelResponse` or
|
|
524
|
+
`AIMessage`.
|
|
517
525
|
"""
|
|
518
526
|
|
|
519
527
|
def __call__(
|
|
@@ -528,7 +536,8 @@ class _CallableReturningModelResponse(Protocol[StateT_contra, ContextT]): # typ
|
|
|
528
536
|
class _CallableReturningToolResponse(Protocol):
|
|
529
537
|
"""Callable for tool call interception with handler callback.
|
|
530
538
|
|
|
531
|
-
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`.
|
|
532
541
|
"""
|
|
533
542
|
|
|
534
543
|
def __call__(
|
|
@@ -621,22 +630,22 @@ def before_model(
|
|
|
621
630
|
Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]
|
|
622
631
|
| AgentMiddleware[StateT, ContextT]
|
|
623
632
|
):
|
|
624
|
-
"""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.
|
|
625
634
|
|
|
626
635
|
Args:
|
|
627
636
|
func: The function to be decorated. Must accept:
|
|
628
637
|
`state: StateT, runtime: Runtime[ContextT]` - State and runtime context
|
|
629
638
|
state_schema: Optional custom state schema type. If not provided, uses the default
|
|
630
|
-
AgentState schema.
|
|
639
|
+
`AgentState` schema.
|
|
631
640
|
tools: Optional list of additional tools to register with this middleware.
|
|
632
641
|
can_jump_to: Optional list of valid jump destinations for conditional edges.
|
|
633
|
-
Valid values are: "tools"
|
|
642
|
+
Valid values are: `"tools"`, `"model"`, `"end"`
|
|
634
643
|
name: Optional name for the generated middleware class. If not provided,
|
|
635
644
|
uses the decorated function's name.
|
|
636
645
|
|
|
637
646
|
Returns:
|
|
638
|
-
Either an AgentMiddleware instance (if func is provided directly) or a
|
|
639
|
-
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.
|
|
640
649
|
|
|
641
650
|
The decorated function should return:
|
|
642
651
|
- `dict[str, Any]` - State updates to merge into the agent state
|
|
@@ -763,22 +772,22 @@ def after_model(
|
|
|
763
772
|
Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]
|
|
764
773
|
| AgentMiddleware[StateT, ContextT]
|
|
765
774
|
):
|
|
766
|
-
"""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.
|
|
767
776
|
|
|
768
777
|
Args:
|
|
769
778
|
func: The function to be decorated. Must accept:
|
|
770
779
|
`state: StateT, runtime: Runtime[ContextT]` - State and runtime context
|
|
771
|
-
state_schema: Optional custom state schema type. If not provided, uses the
|
|
772
|
-
AgentState schema.
|
|
780
|
+
state_schema: Optional custom state schema type. If not provided, uses the
|
|
781
|
+
default `AgentState` schema.
|
|
773
782
|
tools: Optional list of additional tools to register with this middleware.
|
|
774
783
|
can_jump_to: Optional list of valid jump destinations for conditional edges.
|
|
775
|
-
Valid values are: "tools"
|
|
784
|
+
Valid values are: `"tools"`, `"model"`, `"end"`
|
|
776
785
|
name: Optional name for the generated middleware class. If not provided,
|
|
777
786
|
uses the decorated function's name.
|
|
778
787
|
|
|
779
788
|
Returns:
|
|
780
|
-
Either an AgentMiddleware instance (if func is provided) or a decorator
|
|
781
|
-
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.
|
|
782
791
|
|
|
783
792
|
The decorated function should return:
|
|
784
793
|
- `dict[str, Any]` - State updates to merge into the agent state
|
|
@@ -894,22 +903,22 @@ def before_agent(
|
|
|
894
903
|
Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]
|
|
895
904
|
| AgentMiddleware[StateT, ContextT]
|
|
896
905
|
):
|
|
897
|
-
"""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.
|
|
898
907
|
|
|
899
908
|
Args:
|
|
900
909
|
func: The function to be decorated. Must accept:
|
|
901
910
|
`state: StateT, runtime: Runtime[ContextT]` - State and runtime context
|
|
902
|
-
state_schema: Optional custom state schema type. If not provided, uses the
|
|
903
|
-
AgentState schema.
|
|
911
|
+
state_schema: Optional custom state schema type. If not provided, uses the
|
|
912
|
+
default `AgentState` schema.
|
|
904
913
|
tools: Optional list of additional tools to register with this middleware.
|
|
905
914
|
can_jump_to: Optional list of valid jump destinations for conditional edges.
|
|
906
|
-
Valid values are: "tools"
|
|
915
|
+
Valid values are: `"tools"`, `"model"`, `"end"`
|
|
907
916
|
name: Optional name for the generated middleware class. If not provided,
|
|
908
917
|
uses the decorated function's name.
|
|
909
918
|
|
|
910
919
|
Returns:
|
|
911
|
-
Either an AgentMiddleware instance (if func is provided directly) or a
|
|
912
|
-
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.
|
|
913
922
|
|
|
914
923
|
The decorated function should return:
|
|
915
924
|
- `dict[str, Any]` - State updates to merge into the agent state
|
|
@@ -1036,22 +1045,22 @@ def after_agent(
|
|
|
1036
1045
|
Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]
|
|
1037
1046
|
| AgentMiddleware[StateT, ContextT]
|
|
1038
1047
|
):
|
|
1039
|
-
"""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.
|
|
1040
1049
|
|
|
1041
1050
|
Args:
|
|
1042
1051
|
func: The function to be decorated. Must accept:
|
|
1043
1052
|
`state: StateT, runtime: Runtime[ContextT]` - State and runtime context
|
|
1044
|
-
state_schema: Optional custom state schema type. If not provided, uses the
|
|
1045
|
-
AgentState schema.
|
|
1053
|
+
state_schema: Optional custom state schema type. If not provided, uses the
|
|
1054
|
+
default `AgentState` schema.
|
|
1046
1055
|
tools: Optional list of additional tools to register with this middleware.
|
|
1047
1056
|
can_jump_to: Optional list of valid jump destinations for conditional edges.
|
|
1048
|
-
Valid values are: "tools"
|
|
1057
|
+
Valid values are: `"tools"`, `"model"`, `"end"`
|
|
1049
1058
|
name: Optional name for the generated middleware class. If not provided,
|
|
1050
1059
|
uses the decorated function's name.
|
|
1051
1060
|
|
|
1052
1061
|
Returns:
|
|
1053
|
-
Either an AgentMiddleware instance (if func is provided) or a decorator
|
|
1054
|
-
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.
|
|
1055
1064
|
|
|
1056
1065
|
The decorated function should return:
|
|
1057
1066
|
- `dict[str, Any]` - State updates to merge into the agent state
|
|
@@ -1300,21 +1309,21 @@ def wrap_model_call(
|
|
|
1300
1309
|
]
|
|
1301
1310
|
| AgentMiddleware[StateT, ContextT]
|
|
1302
1311
|
):
|
|
1303
|
-
"""Create middleware with wrap_model_call hook from a function.
|
|
1312
|
+
"""Create middleware with `wrap_model_call` hook from a function.
|
|
1304
1313
|
|
|
1305
1314
|
Converts a function with handler callback into middleware that can intercept
|
|
1306
1315
|
model calls, implement retry logic, handle errors, and rewrite responses.
|
|
1307
1316
|
|
|
1308
1317
|
Args:
|
|
1309
1318
|
func: Function accepting (request, handler) that calls handler(request)
|
|
1310
|
-
to execute the model and returns ModelResponse or AIMessage
|
|
1319
|
+
to execute the model and returns `ModelResponse` or `AIMessage`.
|
|
1311
1320
|
Request contains state and runtime.
|
|
1312
|
-
state_schema: Custom state schema. Defaults to AgentState
|
|
1321
|
+
state_schema: Custom state schema. Defaults to `AgentState`.
|
|
1313
1322
|
tools: Additional tools to register with this middleware.
|
|
1314
1323
|
name: Middleware class name. Defaults to function name.
|
|
1315
1324
|
|
|
1316
1325
|
Returns:
|
|
1317
|
-
AgentMiddleware instance if func provided, otherwise a decorator.
|
|
1326
|
+
`AgentMiddleware` instance if func provided, otherwise a decorator.
|
|
1318
1327
|
|
|
1319
1328
|
Examples:
|
|
1320
1329
|
Basic retry logic:
|
|
@@ -1448,20 +1457,20 @@ def wrap_tool_call(
|
|
|
1448
1457
|
]
|
|
1449
1458
|
| AgentMiddleware
|
|
1450
1459
|
):
|
|
1451
|
-
"""Create middleware with wrap_tool_call hook from a function.
|
|
1460
|
+
"""Create middleware with `wrap_tool_call` hook from a function.
|
|
1452
1461
|
|
|
1453
1462
|
Converts a function with handler callback into middleware that can intercept
|
|
1454
1463
|
tool calls, implement retry logic, monitor execution, and modify responses.
|
|
1455
1464
|
|
|
1456
1465
|
Args:
|
|
1457
1466
|
func: Function accepting (request, handler) that calls
|
|
1458
|
-
handler(request) to execute the tool and returns final ToolMessage or
|
|
1459
|
-
Can be sync or async.
|
|
1467
|
+
handler(request) to execute the tool and returns final `ToolMessage` or
|
|
1468
|
+
`Command`. Can be sync or async.
|
|
1460
1469
|
tools: Additional tools to register with this middleware.
|
|
1461
1470
|
name: Middleware class name. Defaults to function name.
|
|
1462
1471
|
|
|
1463
1472
|
Returns:
|
|
1464
|
-
AgentMiddleware instance if func provided, otherwise a decorator.
|
|
1473
|
+
`AgentMiddleware` instance if func provided, otherwise a decorator.
|
|
1465
1474
|
|
|
1466
1475
|
Examples:
|
|
1467
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
|
|