Commit 8aea6dd
authored
feat: support structured output retry middleware (#33663)
* attach the latest `AIMessage` to all `StructuredOutputError`s so that
relevant middleware can use as desired
* raise `StructuredOutputError` from `ProviderStrategy` logic in case of
failed parsing (so that we can retry from middleware)
* added a test suite w/ example custom middleware that retries for tool
+ provider strategy
Long term, we could add our own opinionated structured output retry
middleware, but this at least unblocks folks who want to use custom
retry logic in the short term :)
```py
class StructuredOutputRetryMiddleware(AgentMiddleware):
"""Retries model calls when structured output parsing fails."""
def __init__(self, max_retries: int) -> None:
self.max_retries = max_retries
def wrap_model_call(
self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]
) -> ModelResponse:
for attempt in range(self.max_retries + 1):
try:
return handler(request)
except StructuredOutputError as exc:
if attempt == self.max_retries:
raise
ai_content = exc.ai_message.content
error_message = (
f"Your previous response was:\n{ai_content}\n\n"
f"Error: {exc}. Please try again with a valid response."
)
request.messages.append(HumanMessage(content=error_message))
```1 parent 78a2f86 commit 8aea6dd
File tree
4 files changed
+442
-7
lines changed- libs/langchain_v1
- langchain/agents
- tests/unit_tests/agents
- middleware
4 files changed
+442
-7
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
33 | 33 | | |
34 | 34 | | |
35 | 35 | | |
| 36 | + | |
36 | 37 | | |
37 | 38 | | |
38 | 39 | | |
| |||
797 | 798 | | |
798 | 799 | | |
799 | 800 | | |
800 | | - | |
801 | | - | |
| 801 | + | |
| 802 | + | |
| 803 | + | |
| 804 | + | |
| 805 | + | |
| 806 | + | |
| 807 | + | |
| 808 | + | |
| 809 | + | |
| 810 | + | |
802 | 811 | | |
803 | 812 | | |
804 | 813 | | |
| |||
812 | 821 | | |
813 | 822 | | |
814 | 823 | | |
815 | | - | |
| 824 | + | |
816 | 825 | | |
817 | 826 | | |
818 | 827 | | |
819 | | - | |
| 828 | + | |
820 | 829 | | |
821 | 830 | | |
822 | 831 | | |
| |||
858 | 867 | | |
859 | 868 | | |
860 | 869 | | |
861 | | - | |
| 870 | + | |
862 | 871 | | |
863 | 872 | | |
864 | 873 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
34 | 34 | | |
35 | 35 | | |
36 | 36 | | |
| 37 | + | |
| 38 | + | |
37 | 39 | | |
38 | 40 | | |
39 | 41 | | |
40 | 42 | | |
41 | | - | |
| 43 | + | |
42 | 44 | | |
43 | 45 | | |
44 | 46 | | |
45 | 47 | | |
| 48 | + | |
46 | 49 | | |
47 | 50 | | |
| 51 | + | |
48 | 52 | | |
49 | 53 | | |
50 | 54 | | |
| |||
55 | 59 | | |
56 | 60 | | |
57 | 61 | | |
58 | | - | |
| 62 | + | |
59 | 63 | | |
60 | 64 | | |
61 | 65 | | |
62 | 66 | | |
63 | 67 | | |
| 68 | + | |
64 | 69 | | |
65 | 70 | | |
66 | 71 | | |
| 72 | + | |
67 | 73 | | |
68 | 74 | | |
69 | 75 | | |
| |||
0 commit comments