-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Implement adapter retry for Pydantic Validation Error #8050
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
TomeHirata
wants to merge
18
commits into
stanfordnlp:main
Choose a base branch
from
TomeHirata:feat/retry/pydantic
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 11 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
84c1bfe
implement adapter retry
TomeHirata 5d3d927
lint
TomeHirata 93f4543
use ValueError instead of Validation Error
TomeHirata 181ace4
add demos to tests
TomeHirata 78794ba
avoid forcing all fields in demos
TomeHirata bfd8555
Merge branch 'main' into feat/retry/pydantic
TomeHirata cbb45e2
fix test
TomeHirata f9ccd3a
change default adapter_retry_count to 0
TomeHirata 574c252
introduce RetryAdapter
TomeHirata 27977c6
lint
TomeHirata ae67f49
fix ReAct test
TomeHirata bb4ce17
remove logger
TomeHirata 1e7c9bb
address comment
TomeHirata 6c9b666
merge
TomeHirata 10b9b89
merge main
TomeHirata e013456
merge main
TomeHirata 3e1bebd
fix tests
TomeHirata 96b4b3d
lint
TomeHirata File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,16 @@ | ||
from dspy.adapters.base import Adapter | ||
from dspy.adapters.chat_adapter import ChatAdapter | ||
from dspy.adapters.json_adapter import JSONAdapter | ||
from dspy.adapters.retry_adapter import RetryAdapter | ||
from dspy.adapters.types import Image, History | ||
|
||
DEFAULT_ADAPTER = RetryAdapter(main_adapter=ChatAdapter(), fallback_adapter=JSONAdapter()) | ||
|
||
__all__ = [ | ||
"Adapter", | ||
"ChatAdapter", | ||
"JSONAdapter", | ||
"RetryAdapter", | ||
"Image", | ||
"History", | ||
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,145 @@ | ||
|
||
from typing import TYPE_CHECKING, Any, Optional, Type | ||
import logging | ||
|
||
from dspy.adapters.base import Adapter | ||
from dspy.signatures.signature import Signature | ||
from dspy.adapters.utils import create_signature_for_retry | ||
|
||
if TYPE_CHECKING: | ||
from dspy.clients.lm import LM | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
class RetryAdapter(Adapter): | ||
""" | ||
RetryAdapter is an adapter that retries the execution of another adapter for | ||
a specified number of times if it fails to parse completion outputs. | ||
""" | ||
|
||
def __init__(self, main_adapter: Adapter, fallback_adapter: Optional[Adapter] = None, max_retries: int = 3): | ||
TomeHirata marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Initializes the RetryAdapter. | ||
|
||
Args: | ||
main_adapter (Adapter): The main adapter to use. | ||
fallback_adapter (Optional[Adapter]): The fallback adapter to use if the main adapter fails. | ||
max_retries (int): The maximum number of retries. Defaults to 3. | ||
TomeHirata marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
self.main_adapter = main_adapter | ||
self.fallback_adapter = fallback_adapter | ||
self.max_retries = max_retries | ||
|
||
def __call__( | ||
self, | ||
lm: "LM", | ||
lm_kwargs: dict[str, Any], | ||
signature: Type[Signature], | ||
demos: list[dict[str, Any]], | ||
inputs: dict[str, Any], | ||
) -> list[dict[str, Any]]: | ||
""" | ||
Execute main_adapter and fallback_adapter in the following procedure: | ||
1. Call the main_adapter. | ||
2. If the main_adapter fails, call the fallback_adapter. | ||
3. If the fallback_adapter fails, retry the main_adapter including previous response for `max_retries` times. | ||
TomeHirata marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Args: | ||
lm (LM): The dspy.LM to use. | ||
lm_kwargs (dict[str, Any]): Additional arguments for the lm. | ||
signature (Type[Signature]): The signature of the function. | ||
demos (list[dict[str, Any]]): A list of demo examples. | ||
inputs (dict[str, Any]): A list representating the user input. | ||
|
||
Returns: | ||
A list of parsed completions. The size of the list is equal to `n` argument. Defaults to 1. | ||
|
||
Raises: | ||
Exception: If fail to parse outputs after the maximum number of retries. | ||
""" | ||
outputs = [] | ||
max_retries = max(self.max_retries, 0) | ||
n_completion = lm_kwargs.get("n", 1) | ||
|
||
values, parse_failures = self._call_adapter( | ||
self.main_adapter, | ||
lm, | ||
lm_kwargs, | ||
signature, | ||
demos, | ||
inputs, | ||
) | ||
outputs.extend(values) | ||
|
||
if len(outputs) == n_completion: | ||
return outputs | ||
|
||
lm_kwargs["n"] = n_completion - len(outputs) | ||
TomeHirata marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if self.fallback_adapter is not None: | ||
outputs.extend(self._call_adapter( | ||
self.fallback_adapter, | ||
lm, | ||
lm_kwargs, | ||
signature, | ||
demos, | ||
inputs, | ||
)[0]) | ||
if len(outputs) == n_completion: | ||
return outputs | ||
|
||
# Retry the main adapter with previous response for `max_retries` times | ||
lm_kwargs["n"] = 1 | ||
signature = create_signature_for_retry(signature) | ||
if parse_failures: | ||
inputs["previous_response"] = parse_failures[0][0] | ||
inputs["error_message"] = str(parse_failures[0][1]) | ||
for i in range(max_retries): | ||
values, parse_failures = self._call_adapter( | ||
self.main_adapter, | ||
lm, | ||
lm_kwargs, | ||
signature, | ||
demos, | ||
inputs, | ||
) | ||
outputs.extend(values) | ||
if len(outputs) == n_completion: | ||
return outputs | ||
logger.warning(f"Retry {i+1}/{max_retries} for {self.main_adapter.__class__.__name__} failed with error: {parse_failures[0][1]}") | ||
inputs["previous_response"] = parse_failures[0][0] | ||
inputs["error_message"] = str(parse_failures[0][1]) | ||
|
||
# raise the last error | ||
raise ValueError("Failed to parse LM outputs for maximum retries.") from parse_failures[0][1] | ||
|
||
def _call_adapter( | ||
self, | ||
adapter: Adapter, | ||
lm: "LM", | ||
lm_kwargs: dict[str, Any], | ||
signature: Type[Signature], | ||
demos: list[dict[str, Any]], | ||
inputs: dict[str, Any], | ||
): | ||
values = [] | ||
parse_failures = [] | ||
messages = adapter.format(signature=signature, demos=demos, inputs=inputs) | ||
outputs = lm(messages=messages, **lm_kwargs) | ||
for i, output in enumerate(outputs): | ||
try: | ||
output_logprobs = None | ||
|
||
if isinstance(output, dict): | ||
output, output_logprobs = output["text"], output["logprobs"] | ||
|
||
value = adapter.parse(signature, output) | ||
|
||
if output_logprobs is not None: | ||
value["logprobs"] = output_logprobs | ||
|
||
values.append(value) | ||
except ValueError as e: | ||
logger.warning(f"Failed to parse the {i+1}/{lm_kwargs.get('n', 1)} LM output with adapter {adapter.__class__.__name__}. Error: {e}") | ||
parse_failures.append((outputs[i], e)) | ||
|
||
return values, parse_failures |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.