-
Notifications
You must be signed in to change notification settings - Fork 9
Add three types of validators #47
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
Temerius
wants to merge
7
commits into
LamoomAI:main
Choose a base branch
from
Temerius:main
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 all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a4b4269
add three types of validators (JSON, XML, YAML)
141902d
Merge remote-tracking branch 'upstream/main'
b271d50
reset changes (in out of notebook)
fbdec60
fix all remarks + add integrational tests
b0105f9
add method attach_to prompt and add_field_to_validate
9f3ecab
Merge remote-tracking branch 'upstream/main'
f7202ac
add dump, load methods for validator class, rename call_and_validate …
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 |
|---|---|---|
|
|
@@ -10,4 +10,8 @@ dist | |
| .vscode | ||
| .pytest_cache | ||
| python | ||
| .env.test | ||
| .env.test | ||
| test.py | ||
| test2.py | ||
| main.py | ||
| lamoom_venv/ | ||
Large diffs are not rendered by default.
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
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 |
|---|---|---|
|
|
@@ -4,7 +4,8 @@ | |
| from decimal import Decimal | ||
| import requests | ||
| import time | ||
| from lamoom.settings import LAMOOM_API_URI | ||
| import json | ||
| from lamoom.settings import LAMOOM_API_URI, PROMPT_VALIDATORS | ||
| from lamoom import Secrets, settings | ||
| from lamoom.ai_models.ai_model import AI_MODELS_PROVIDER | ||
| from lamoom.ai_models.attempt_to_call import AttemptToCall | ||
|
|
@@ -16,7 +17,8 @@ | |
|
|
||
| from lamoom.exceptions import ( | ||
| LamoomPromptIsnotFoundError, | ||
| RetryableCustomError | ||
| RetryableCustomError, | ||
| ValidatorException | ||
| ) | ||
| from lamoom.services.SaveWorker import SaveWorker | ||
| from lamoom.prompt.prompt import Prompt | ||
|
|
@@ -25,8 +27,7 @@ | |
| from lamoom.responses import AIResponse | ||
| from lamoom.services.lamoom import LamoomService | ||
| from lamoom.utils import current_timestamp_ms | ||
| import json | ||
|
|
||
| from lamoom.validators import Validator | ||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
|
|
@@ -220,7 +221,7 @@ def init_behavior(self, model: str, provider_url: str = None) -> AIModelsBehavio | |
| fallback_attempts=fallback_attempts | ||
| ) | ||
|
|
||
| def call( | ||
| def call_llm( | ||
| self, | ||
| prompt_id: str, | ||
| context: t.Dict[str, str], | ||
|
|
@@ -310,6 +311,99 @@ def call( | |
| "Prompt call failed, no attempts worked" | ||
| ) | ||
| raise Exception | ||
|
|
||
|
|
||
| def call( | ||
| self, | ||
| prompt_id: str, | ||
| context: t.Dict[str, str], | ||
| model: str, | ||
| provider_url: str = None, | ||
| params: t.Dict[str, t.Any] = {}, | ||
| version: str = None, | ||
| count_of_retries: int = 5, | ||
| test_data: dict = {}, | ||
| stream_function: t.Callable = None, | ||
| check_connection: t.Callable = None, | ||
| stream_params: dict = {}, | ||
| ) -> AIResponse: | ||
|
|
||
| max_attempts = 1 | ||
| validators = PROMPT_VALIDATORS.get(prompt_id) | ||
| if validators is None: | ||
| validators = [] | ||
| else: | ||
| validators = validators.values() | ||
| for validator in validators: | ||
| max_attempts += min(sum(map(int, validator.retry_rules.values())), validator.retry) | ||
|
|
||
| total_results: t.List[AIResponse] = [] | ||
| total_errors: t.List[dict] = [] | ||
|
|
||
| for iteration in range(max_attempts): | ||
| result = None | ||
| try: | ||
| result = self.call_llm( | ||
| prompt_id=prompt_id, | ||
| context=context, | ||
| model=model, | ||
| provider_url=provider_url, | ||
| params=params, | ||
| version=version, | ||
| count_of_retries=count_of_retries, | ||
| test_data=test_data, | ||
| stream_function=stream_function, | ||
| check_connection=check_connection, | ||
| stream_params=stream_params | ||
| ) | ||
| except Exception as e: | ||
| logger.error(f"Attempt {iteration + 1} failed with error: {str(e)}") | ||
| if result is None: | ||
| result = AIResponse() | ||
| result.errors = [{ | ||
| "iteration": iteration, | ||
| "error": str(e) | ||
| }] | ||
| break | ||
|
|
||
| validation_failed = False | ||
| can_retry = False | ||
|
|
||
| validation_errors = [] | ||
| for validator in validators: | ||
| validator.validate(result) | ||
| if validator.has_errors(): | ||
| validation_failed = True | ||
| for error in validator.get_errors(): | ||
| validation_errors.append({ | ||
| "id": validator.id, | ||
| "iteration": iteration, | ||
| "error": validator.format_error(error) | ||
| }) | ||
| if validator.can_retry(): | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I like that you made that logic isolated |
||
| can_retry = True | ||
| else: | ||
| total_errors.extend(validation_errors) | ||
| break | ||
|
|
||
| result.errors = validation_errors if validation_errors else None | ||
| total_results.append(result) | ||
|
|
||
| if validation_failed: | ||
| if can_retry and iteration < max_attempts - 1: | ||
| logger.info(f"Validation errors occurred, retrying (attempt {iteration + 1}/{max_attempts})") | ||
| continue | ||
| else: | ||
| error_messages = [e["error"] for e in validation_errors[-len(validators):]] | ||
| logger.error(f"Validation failed: {', '.join(error_messages)}") | ||
| raise ValidatorException() | ||
| else: | ||
| total_results[-1].attemps = total_results[:-1] | ||
| return total_results[-1] | ||
|
|
||
| logger.error("All attempts failed") | ||
| raise Exception("All attempts failed. Errors: " + ", ".join([e["error"] for e in total_errors])) | ||
|
|
||
|
|
||
| def get_prompt(self, prompt_id: str, version: str = None) -> Prompt: | ||
| """ | ||
|
|
||
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
we need to add here validator's id/name