-
Notifications
You must be signed in to change notification settings - Fork 82
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
rfc: @ls.pytest.mark.parametrize interface #1199
Draft
baskaryan
wants to merge
2
commits into
main
Choose a base branch
from
bagatur/rfc_ls_parametrize
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.
+103
−1
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 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
Empty file.
This file contains 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,93 @@ | ||
from __future__ import annotations | ||
|
||
import inspect | ||
from typing import Any, Callable, Optional | ||
|
||
import pytest | ||
|
||
from langsmith import evaluate | ||
from langsmith.evaluation._runner import TARGET_T | ||
|
||
|
||
def parametrize( | ||
dataset_name: str, | ||
target_fn: TARGET_T, | ||
*, | ||
client: Optional[Any] = None, | ||
max_concurrency: Optional[int] = None, | ||
) -> Callable: | ||
"""Decorator to parametrize a test function with LangSmith dataset examples. | ||
|
||
Args: | ||
dataset_name: Name of the LangSmith dataset to use | ||
target_fn: Function to test that takes inputs dict and returns outputs dict | ||
client: Optional LangSmith client to use | ||
max_concurrency: Optional max number of concurrent evaluations | ||
|
||
Returns: | ||
Decorated test function that will be parametrized with dataset examples. | ||
""" | ||
|
||
def decorator(test_fn: Callable) -> Callable: | ||
# Verify test function signature | ||
sig = inspect.signature(test_fn) | ||
required_params = {"inputs", "outputs", "reference_outputs"} | ||
if not all(param in sig.parameters for param in required_params): | ||
raise ValueError(f"Test function must accept parameters: {required_params}") | ||
|
||
def evaluator(run, example): | ||
"""Evaluator that runs the test function and returns pass/fail result.""" | ||
try: | ||
results = test_fn( | ||
inputs=example.inputs, | ||
outputs=run.outputs, | ||
reference_outputs=example.outputs, | ||
) | ||
except AssertionError as e: | ||
return {"score": 0.0, "key": "pass", "comment": str(e)} | ||
except Exception as e: | ||
return { | ||
"score": 0.0, | ||
"key": "pass", | ||
"comment": f"Unexpected error: {str(e)}", | ||
} | ||
else: | ||
if not results: | ||
return {"score": 1.0, "key": "pass"} | ||
elif "results" not in results: | ||
results = {"results": results} | ||
else: | ||
pass | ||
results["results"].append({"score": 1.0, "key": "pass"}) | ||
return results | ||
|
||
@pytest.mark.parametrize( | ||
"example_result", | ||
evaluate( | ||
target_fn, | ||
data=dataset_name, | ||
evaluators=[evaluator], | ||
client=client, | ||
max_concurrency=max_concurrency, | ||
experiment_prefix=f"pytest_{test_fn.__name__}", | ||
blocking=False, | ||
), | ||
) | ||
# @functools.wraps(test_fn) | ||
def wrapped(example_result): | ||
"""Wrapped test function that gets parametrized with results.""" | ||
# Fail the test if the evaluation failed | ||
eval_results = example_result["evaluation_results"]["results"] | ||
if not eval_results: | ||
pytest.fail("No evaluation results") | ||
|
||
pass_result = [r for r in eval_results if r.key == "pass"][0] | ||
if not pass_result.score: | ||
error = pass_result.comment | ||
pytest.fail( | ||
f"Test failed for example {example_result['example'].id}: {error}" | ||
) | ||
|
||
return wrapped | ||
|
||
return decorator |
This file contains 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,7 @@ | ||
import langsmith as ls | ||
|
||
|
||
@ls.pytest.mark.parametrize("Sample Dataset 3", (lambda x: x)) | ||
def test_parametrize(inputs, outputs, reference_outputs) -> list: | ||
assert inputs == outputs | ||
return [{"key": "foo", "value": "bar"}] |
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.
How would you set failure conditions? I assume people don't want to actually fail if any evaluation fails?
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.
which might mean allowing customizability on the interface on this
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.
this only fails if the actual test raises an error (we need to add a manual pytest.fail for that bc we catch and log all errors in the wrapper L48). so it is customizable by default