autoevals 0.0.2__tar.gz → 0.0.3__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 BrainTrust Data
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,190 @@
1
+ Metadata-Version: 2.1
2
+ Name: autoevals
3
+ Version: 0.0.3
4
+ Summary: Universal library for evaluating AI models
5
+ Home-page: https://www.braintrustdata.com
6
+ Author: BrainTrust
7
+ Author-email: info@braintrustdata.com
8
+ Project-URL: Bug Tracker, https://github.com/braintrustdata/autoevals
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.9.0
12
+ Description-Content-Type: text/markdown
13
+ Provides-Extra: dev
14
+ Provides-Extra: doc
15
+ Provides-Extra: all
16
+ License-File: LICENSE
17
+
18
+ # AutoEvals
19
+
20
+ AutoEvals is a tool to quickly and easily evaluate AI model outputs.
21
+
22
+ It bundles together a variety of automatic evaluation methods including:
23
+
24
+ - Heuristic (e.g. Levenshtein distance)
25
+ - Statistical (e.g. BLEU)
26
+ - Model-based (using LLMs)
27
+
28
+ AutoEvals is developed by the team at [BrainTrust](https://braintrustdata.com/).
29
+
30
+ AutoEvals uses model-graded evaluation for a variety of subjective tasks including fact checking,
31
+ safety, and more. Many of these evaluations are adapted from OpenAI's excellent [evals](https://github.com/openai/evals)
32
+ project but are implemented so you can flexibly run them on individual examples, tweak the prompts, and debug
33
+ their outputs.
34
+
35
+ You can also create your own model-graded evaluations with AutoEvals. It's easy to add custom prompts, parse outputs,
36
+ and manage exceptions.
37
+
38
+ ## Installation
39
+
40
+ To install AutoEvals, run the following command:
41
+
42
+ ```bash
43
+ pip install autoevals
44
+ ```
45
+
46
+ ## Example
47
+
48
+ Use AutoEvals to model-grade an example LLM completion using the [factuality prompt](src/autoevals/templates/factuality.yaml).
49
+
50
+ ```python
51
+ from autoevals.llm import *
52
+
53
+ # Create a new LLM-based evaluator
54
+ evaluator = Factuality()
55
+
56
+ # Evaluate an example LLM completion
57
+ input = "Which country has the highest population?"
58
+ output = "People's Republic of China"
59
+ expected = "China"
60
+
61
+ result = evaluator(output, expected, input=input)
62
+
63
+ # The evaluator returns a score from [0,1] and includes the raw outputs from the evaluator
64
+ print(f"Factuality score: {result.score}")
65
+ print(f"Factuality metadata: {result.metadata['rationale']}")
66
+ ```
67
+
68
+ ## Using Braintrust with AutoEvals
69
+
70
+ Once you grade an output using AutoEvals, it's convenient to use [BrainTrust](https://www.braintrustdata.com/docs/libs/python) to log and compare your evaluation results.
71
+
72
+ ```python
73
+ from autoevals.llm import *
74
+ import braintrust
75
+
76
+ # Create a new LLM-based evaluator
77
+ evaluator = Factuality()
78
+
79
+ # Evaluate an example LLM completion
80
+ input = "Which country has the highest population?"
81
+ output = "People's Republic of China"
82
+ expected = "China"
83
+
84
+ result = evaluator(output, expected, input=input)
85
+
86
+ # The evaluator returns a score from [0,1] and includes the raw outputs from the evaluator
87
+ print(f"Factuality score: {result.score}")
88
+ print(f"Factuality metadata: {result.metadata['rationale']}")
89
+
90
+ # Log the evaluation results to BrainTrust
91
+ experiment = braintrust.init(
92
+ project="AutoEvals", api_key="YOUR_BRAINTRUST_API_KEY"
93
+ )
94
+ experiment.log(
95
+ inputs={"query": input},
96
+ output=output,
97
+ expected=expected,
98
+ scores={
99
+ "factuality": result.score,
100
+ },
101
+ metadata={
102
+ "factuality": result.metadata,
103
+ },
104
+ )
105
+ print(experiment.summarize())
106
+ ```
107
+
108
+ ## Supported Evaluation Methods
109
+
110
+ ### Model-Based Classification
111
+
112
+ - Battle
113
+ - ClosedQA
114
+ - Humor
115
+ - Factuality
116
+ - Security
117
+ - Summarization
118
+ - SQL
119
+ - Translation
120
+ - [ ] Fine-tuned binary classifiers
121
+
122
+ ### Embeddings
123
+
124
+ - [ ] BERTScore
125
+ - [ ] Ada Embedding distance
126
+
127
+ ### Heuristic
128
+
129
+ - Levenshtein distance
130
+ - [ ] Jaccard distance
131
+ - [ ] JSON diff
132
+
133
+ ### Statistical
134
+
135
+ - [ ] BLEU
136
+ - [ ] ROUGE
137
+ - [ ] METEOR
138
+
139
+ ## Custom Evaluation Prompts
140
+
141
+ AutoEvals supports custom evaluation prompts for model-graded evaluation. To use them, simply pass in a prompt and scoring mechanism:
142
+
143
+ ```python
144
+ from autoevals import LLMClassifier
145
+
146
+ # Define a prompt prefix for a LLMClassifier (returns just one answer)
147
+ prompt_prefix = """
148
+ You are a technical project manager who helps software engineers generate better titles for their GitHub issues.
149
+ You will look at the issue description, and pick which of two titles better describes it.
150
+
151
+ I'm going to provide you with the issue description, and two possible titles.
152
+
153
+ Issue Description: {{input}}
154
+
155
+ 1: {{output}}
156
+ 2: {{expected}}
157
+ """
158
+
159
+ # Define the scoring mechanism
160
+ # 1 if the generated answer is better than the expected answer
161
+ # 0 otherwise
162
+ output_scores = {"1": 1, "2": 0}
163
+
164
+ evaluator = LLMClassifier(
165
+ prompt_prefix,
166
+ output_scores,
167
+ use_cot=False,
168
+ )
169
+
170
+ # Evaluate an example LLM completion
171
+ page_content = """
172
+ As suggested by Nicolo, we should standardize the error responses coming from GoTrue, postgres, and realtime (and any other/future APIs) so that it's better DX when writing a client,
173
+ We can make this change on the servers themselves, but since postgrest and gotrue are fully/partially external may be harder to change, it might be an option to transform the errors within the client libraries/supabase-js, could be messy?
174
+ Nicolo also dropped this as a reference: http://spec.openapis.org/oas/v3.0.3#openapi-specification"""
175
+ output = (
176
+ "Standardize error responses from GoTrue, Postgres, and Realtime APIs for better DX"
177
+ )
178
+ expected = "Standardize Error Responses across APIs"
179
+
180
+ response = evaluator(output, expected, input=page_content)
181
+
182
+ print(f"Score: {response.score}")
183
+ print(f"Metadata: {response.metadata}")
184
+ ```
185
+
186
+ ## Typescript / Node Support
187
+
188
+ Since AutoEvals has a very simple prompt template format, it is easy to support in other languages, like
189
+ Typescript (and eventually others). We'll support an npm package soon, but in the meantime, feel free to
190
+ grab model templates from the [prompt templates](/src/autoevals/templates) directory.
@@ -0,0 +1,173 @@
1
+ # AutoEvals
2
+
3
+ AutoEvals is a tool to quickly and easily evaluate AI model outputs.
4
+
5
+ It bundles together a variety of automatic evaluation methods including:
6
+
7
+ - Heuristic (e.g. Levenshtein distance)
8
+ - Statistical (e.g. BLEU)
9
+ - Model-based (using LLMs)
10
+
11
+ AutoEvals is developed by the team at [BrainTrust](https://braintrustdata.com/).
12
+
13
+ AutoEvals uses model-graded evaluation for a variety of subjective tasks including fact checking,
14
+ safety, and more. Many of these evaluations are adapted from OpenAI's excellent [evals](https://github.com/openai/evals)
15
+ project but are implemented so you can flexibly run them on individual examples, tweak the prompts, and debug
16
+ their outputs.
17
+
18
+ You can also create your own model-graded evaluations with AutoEvals. It's easy to add custom prompts, parse outputs,
19
+ and manage exceptions.
20
+
21
+ ## Installation
22
+
23
+ To install AutoEvals, run the following command:
24
+
25
+ ```bash
26
+ pip install autoevals
27
+ ```
28
+
29
+ ## Example
30
+
31
+ Use AutoEvals to model-grade an example LLM completion using the [factuality prompt](src/autoevals/templates/factuality.yaml).
32
+
33
+ ```python
34
+ from autoevals.llm import *
35
+
36
+ # Create a new LLM-based evaluator
37
+ evaluator = Factuality()
38
+
39
+ # Evaluate an example LLM completion
40
+ input = "Which country has the highest population?"
41
+ output = "People's Republic of China"
42
+ expected = "China"
43
+
44
+ result = evaluator(output, expected, input=input)
45
+
46
+ # The evaluator returns a score from [0,1] and includes the raw outputs from the evaluator
47
+ print(f"Factuality score: {result.score}")
48
+ print(f"Factuality metadata: {result.metadata['rationale']}")
49
+ ```
50
+
51
+ ## Using Braintrust with AutoEvals
52
+
53
+ Once you grade an output using AutoEvals, it's convenient to use [BrainTrust](https://www.braintrustdata.com/docs/libs/python) to log and compare your evaluation results.
54
+
55
+ ```python
56
+ from autoevals.llm import *
57
+ import braintrust
58
+
59
+ # Create a new LLM-based evaluator
60
+ evaluator = Factuality()
61
+
62
+ # Evaluate an example LLM completion
63
+ input = "Which country has the highest population?"
64
+ output = "People's Republic of China"
65
+ expected = "China"
66
+
67
+ result = evaluator(output, expected, input=input)
68
+
69
+ # The evaluator returns a score from [0,1] and includes the raw outputs from the evaluator
70
+ print(f"Factuality score: {result.score}")
71
+ print(f"Factuality metadata: {result.metadata['rationale']}")
72
+
73
+ # Log the evaluation results to BrainTrust
74
+ experiment = braintrust.init(
75
+ project="AutoEvals", api_key="YOUR_BRAINTRUST_API_KEY"
76
+ )
77
+ experiment.log(
78
+ inputs={"query": input},
79
+ output=output,
80
+ expected=expected,
81
+ scores={
82
+ "factuality": result.score,
83
+ },
84
+ metadata={
85
+ "factuality": result.metadata,
86
+ },
87
+ )
88
+ print(experiment.summarize())
89
+ ```
90
+
91
+ ## Supported Evaluation Methods
92
+
93
+ ### Model-Based Classification
94
+
95
+ - Battle
96
+ - ClosedQA
97
+ - Humor
98
+ - Factuality
99
+ - Security
100
+ - Summarization
101
+ - SQL
102
+ - Translation
103
+ - [ ] Fine-tuned binary classifiers
104
+
105
+ ### Embeddings
106
+
107
+ - [ ] BERTScore
108
+ - [ ] Ada Embedding distance
109
+
110
+ ### Heuristic
111
+
112
+ - Levenshtein distance
113
+ - [ ] Jaccard distance
114
+ - [ ] JSON diff
115
+
116
+ ### Statistical
117
+
118
+ - [ ] BLEU
119
+ - [ ] ROUGE
120
+ - [ ] METEOR
121
+
122
+ ## Custom Evaluation Prompts
123
+
124
+ AutoEvals supports custom evaluation prompts for model-graded evaluation. To use them, simply pass in a prompt and scoring mechanism:
125
+
126
+ ```python
127
+ from autoevals import LLMClassifier
128
+
129
+ # Define a prompt prefix for a LLMClassifier (returns just one answer)
130
+ prompt_prefix = """
131
+ You are a technical project manager who helps software engineers generate better titles for their GitHub issues.
132
+ You will look at the issue description, and pick which of two titles better describes it.
133
+
134
+ I'm going to provide you with the issue description, and two possible titles.
135
+
136
+ Issue Description: {{input}}
137
+
138
+ 1: {{output}}
139
+ 2: {{expected}}
140
+ """
141
+
142
+ # Define the scoring mechanism
143
+ # 1 if the generated answer is better than the expected answer
144
+ # 0 otherwise
145
+ output_scores = {"1": 1, "2": 0}
146
+
147
+ evaluator = LLMClassifier(
148
+ prompt_prefix,
149
+ output_scores,
150
+ use_cot=False,
151
+ )
152
+
153
+ # Evaluate an example LLM completion
154
+ page_content = """
155
+ As suggested by Nicolo, we should standardize the error responses coming from GoTrue, postgres, and realtime (and any other/future APIs) so that it's better DX when writing a client,
156
+ We can make this change on the servers themselves, but since postgrest and gotrue are fully/partially external may be harder to change, it might be an option to transform the errors within the client libraries/supabase-js, could be messy?
157
+ Nicolo also dropped this as a reference: http://spec.openapis.org/oas/v3.0.3#openapi-specification"""
158
+ output = (
159
+ "Standardize error responses from GoTrue, Postgres, and Realtime APIs for better DX"
160
+ )
161
+ expected = "Standardize Error Responses across APIs"
162
+
163
+ response = evaluator(output, expected, input=page_content)
164
+
165
+ print(f"Score: {response.score}")
166
+ print(f"Metadata: {response.metadata}")
167
+ ```
168
+
169
+ ## Typescript / Node Support
170
+
171
+ Since AutoEvals has a very simple prompt template format, it is easy to support in other languages, like
172
+ Typescript (and eventually others). We'll support an npm package soon, but in the meantime, feel free to
173
+ grab model templates from the [prompt templates](/src/autoevals/templates) directory.
@@ -32,13 +32,20 @@ class Evaluator(ABC):
32
32
  return Evaluation(0, error=e)
33
33
 
34
34
  def eval(self, output, expected=None, **kwargs):
35
- return asyncio.run(self.eval_async(output, expected, **kwargs))
35
+ try:
36
+ return self._run_eval_sync(output, expected, **kwargs)
37
+ except Exception as e:
38
+ return Evaluation(0, error=e)
36
39
 
37
40
  def __call__(self, output, expected=None, **kwargs):
38
41
  return self.eval(output, expected, **kwargs)
39
42
 
40
- @abstractmethod
41
43
  async def _run_eval_async(self, output, expected=None, **kwargs) -> Evaluation:
44
+ # By default we just run the sync version in a thread
45
+ return self._run_eval_sync(output, expected, **kwargs)
46
+
47
+ @abstractmethod
48
+ async def _run_eval_sync(self, output, expected=None, **kwargs) -> Evaluation:
42
49
  ...
43
50
 
44
51
 
@@ -10,7 +10,7 @@ from .base import Evaluation, Evaluator
10
10
 
11
11
 
12
12
  SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
13
- MODEL_TEMPLATES = set(["Battle", "ClosedQA", "Humor", "Fact", "Possible", "Security", "Translation"])
13
+ MODEL_TEMPLATES = set(["Battle", "ClosedQA", "Humor", "Factuality", "Possible", "Security", "Summary", "Translation"])
14
14
 
15
15
 
16
16
  NO_COT_SUFFIX = """\
@@ -39,14 +39,17 @@ class GuidanceLLMClassifier(Evaluator):
39
39
  def __init__(self, program: Union[str, guidance.Program], parse_score_fn, choice_scores):
40
40
  if isinstance(program, str):
41
41
  program = guidance.Program(program)
42
+
43
+ if program.llm is None:
44
+ raise ValueError("GuidanceLLMClassifier requires an LLM")
45
+
42
46
  self.program = program
43
47
  self.parse_score_fn = parse_score_fn
44
48
  self.choice_scores = choice_scores
45
49
 
46
- async def _run_eval_async(self, output, expected, **kwargs):
50
+ def _process_response(self, resp):
47
51
  metadata = {}
48
52
  try:
49
- resp = await self.program(output=output, expected=expected, async_mode=True, **kwargs)
50
53
  metadata["rationale"] = str(resp)
51
54
  metadata["choice"] = self.parse_score_fn(resp)
52
55
  score = self.choice_scores[metadata["choice"]]
@@ -57,6 +60,20 @@ class GuidanceLLMClassifier(Evaluator):
57
60
 
58
61
  return Evaluation(score=score, metadata=metadata, error=error)
59
62
 
63
+ async def _run_eval_async(self, output, expected, **kwargs):
64
+ try:
65
+ resp = await self.program(output=output, expected=expected, async_mode=True, **kwargs)
66
+ return self._process_response(resp)
67
+ except Exception as e:
68
+ return Evaluation(score=0, error=e)
69
+
70
+ def _run_eval_sync(self, output, expected, **kwargs):
71
+ try:
72
+ resp = self.program(output=output, expected=expected, async_mode=False, **kwargs)
73
+ return self._process_response(resp)
74
+ except Exception as e:
75
+ return Evaluation(score=0, error=e)
76
+
60
77
 
61
78
  @dataclass
62
79
  class ModelGradedSpec:
@@ -94,7 +111,7 @@ class LLMClassifier(GuidanceLLMClassifier):
94
111
  def parse_score_fn(resp):
95
112
  answer = None
96
113
 
97
- answers = re.findall("Answer\s*=\s*(.*)", resp["answer"], re.MULTILINE)
114
+ answers = re.findall(r"Answer\s*=\s*(.*)", resp["answer"], re.MULTILINE)
98
115
  if len(answers) > 0:
99
116
  answer = answers[-1].strip()
100
117
  elif resp["answer"].strip() in choice_strings:
@@ -140,16 +157,7 @@ class LLMClassifier(GuidanceLLMClassifier):
140
157
  return cls.from_spec(ModelGradedSpec(**spec), **kwargs)
141
158
 
142
159
 
143
- def __getattr__(name: str) -> Any:
144
- if name not in MODEL_TEMPLATES:
145
- return AttributeError
146
-
147
- # convert FooBar to foo_bar
148
- template_name = re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower() + ".yaml"
149
-
150
- if not os.path.exists(os.path.join(SCRIPT_DIR, "templates", template_name)):
151
- raise AttributeError(f"Model template {name} not found")
152
-
160
+ def _build_template_class(name: str):
153
161
  class C(LLMClassifier):
154
162
  def __new__(cls, model=None, use_cot=None, max_tokens=None, temperature=None):
155
163
  kwargs = {}
@@ -162,9 +170,18 @@ def __getattr__(name: str) -> Any:
162
170
  if temperature is not None:
163
171
  kwargs["temperature"] = temperature
164
172
 
173
+ # convert FooBar to foo_bar
174
+ template_name = re.sub(r"(?<!^)(?=[A-Z])", "_", name).lower() + ".yaml"
175
+
176
+ if not os.path.exists(os.path.join(SCRIPT_DIR, "templates", template_name)):
177
+ raise AttributeError(f"Model template {name} not found")
178
+
165
179
  return LLMClassifier.from_spec_file(os.path.join(SCRIPT_DIR, "templates", template_name), **kwargs)
166
180
 
167
181
  return C
168
182
 
169
183
 
184
+ for model in MODEL_TEMPLATES:
185
+ globals()[model] = _build_template_class(model)
186
+
170
187
  __all__ = ["GuidanceLLMClassifier", "LLMClassifier"] + list(MODEL_TEMPLATES)
@@ -4,11 +4,15 @@ from .base import Evaluator
4
4
 
5
5
 
6
6
  class LevenshteinEvaluator(Evaluator):
7
- async def _run_eval_async(self, output, expected=None, **kwargs):
7
+ async def _run_eval_sync(self, output, expected=None, **kwargs):
8
8
  if expected is None:
9
9
  raise ValueError("LevenshteinEvaluator requires an expected value")
10
10
 
11
11
  output, expected = str(output), str(expected)
12
+ max_len = max(len(x) for x in [output, expected])
13
+ if max_len == 0:
14
+ return 1
15
+
12
16
  return 1 - (distance(output, expected) / max(len(x) for x in [output, expected]))
13
17
 
14
18
 
@@ -0,0 +1,130 @@
1
+ import os
2
+
3
+ import diskcache
4
+ from guidance.llms.caches import DiskCache
5
+
6
+
7
+ # By default, guidance uses the user's cache directory (e.g. in the Library/Caches dir on macOS)
8
+ # However, we'd like to cache (and commit) the results of our tests, so we monkey patch the library
9
+ # to use a cache directory in the project root.
10
+ _SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
11
+ CACHE_DIR = os.path.join(_SCRIPT_DIR, "../../.testcache")
12
+ os.makedirs(CACHE_DIR, exist_ok=True)
13
+
14
+
15
+ def diskcache_init(self, llm_name: str):
16
+ self._diskcache = diskcache.Cache(os.path.join(CACHE_DIR, f"_{llm_name}.diskcache"))
17
+
18
+
19
+ DiskCache.__init__ = diskcache_init
20
+
21
+
22
+ import asyncio
23
+ import re
24
+
25
+ import guidance
26
+
27
+ from autoevals.llm import *
28
+
29
+
30
+ def test_guidance():
31
+ def parse_best_title(grade):
32
+ return int(re.findall(r"Winner: (\d+)", grade["summary"])[0])
33
+
34
+ e = GuidanceLLMClassifier(
35
+ guidance(
36
+ """
37
+ {{#system~}}
38
+ You are a technical project manager who helps software engineers generate better titles for their GitHub issues.
39
+ You will look at the issue description, and pick which of two titles better describes it.
40
+ {{~/system}}
41
+
42
+ {{#user~}}
43
+ I'm going to provide you with the issue description, and two possible titles.
44
+
45
+ Issue Description: {{page_content}}
46
+
47
+ Title 1: {{output}}
48
+ Title 2: {{expected}}
49
+
50
+ Please discuss each title briefly (one line for pros, one for cons), and then pick which one you think more accurately
51
+ summarizes the issue by writing "Winner: 1" or "Winner: 2", and then a short rationale for your choice.
52
+ {{~/user}}
53
+
54
+ {{#assistant~}}
55
+ {{gen 'summary' max_tokens=__max_tokens temperature=0}}
56
+ {{~/assistant}}""",
57
+ llm=guidance.llms.OpenAI("gpt-3.5-turbo"),
58
+ ),
59
+ parse_best_title,
60
+ {1: 1, 2: 0},
61
+ )
62
+
63
+ page_content = """
64
+ As suggested by Nicolo, we should standardize the error responses coming from GoTrue, postgres, and realtime (and any other/future APIs) so that it's better DX when writing a client,
65
+
66
+ We can make this change on the servers themselves, but since postgrest and gotrue are fully/partially external may be harder to change, it might be an option to transform the errors within the client libraries/supabase-js, could be messy?
67
+
68
+ Nicolo also dropped this as a reference: http://spec.openapis.org/oas/v3.0.3#openapi-specification"""
69
+
70
+ gen_title = "Standardize error responses from GoTrue, Postgres, and Realtime APIs for better DX"
71
+ original_title = "Standardize Error Responses across APIs"
72
+
73
+ response = e(gen_title, original_title, page_content=page_content, __max_tokens=500)
74
+ print(response.as_json(indent=2))
75
+ assert response.score == 1
76
+ assert response.error is None
77
+
78
+
79
+ def test_llm_classifier():
80
+ for use_cot in [True, False]:
81
+ e = LLMClassifier(
82
+ """
83
+ You are a technical project manager who helps software engineers generate better titles for their GitHub issues.
84
+ You will look at the issue description, and pick which of two titles better describes it.
85
+
86
+ I'm going to provide you with the issue description, and two possible titles.
87
+
88
+ Issue Description: {{page_content}}
89
+
90
+ 1: {{output}}
91
+ 2: {{expected}}
92
+
93
+ Please discuss each title briefly (one line for pros, one for cons).
94
+ """,
95
+ {"1": 1, "2": 0},
96
+ use_cot=use_cot,
97
+ )
98
+
99
+ page_content = """
100
+ As suggested by Nicolo, we should standardize the error responses coming from GoTrue, postgres, and realtime (and any other/future APIs) so that it's better DX when writing a client,
101
+
102
+ We can make this change on the servers themselves, but since postgrest and gotrue are fully/partially external may be harder to change, it might be an option to transform the errors within the client libraries/supabase-js, could be messy?
103
+
104
+ Nicolo also dropped this as a reference: http://spec.openapis.org/oas/v3.0.3#openapi-specification"""
105
+
106
+ gen_title = "Standardize error responses from GoTrue, Postgres, and Realtime APIs for better DX"
107
+ original_title = "Standardize Error Responses across APIs"
108
+
109
+ response = e(gen_title, original_title, page_content=page_content)
110
+ print(response.as_json(indent=2))
111
+ assert response.score == 1
112
+ assert response.error is None
113
+
114
+
115
+ def test_nested_async():
116
+ async def nested_async():
117
+ e = Battle()
118
+ e(instructions="Add the following numbers: 1, 2, 3", output="7", expected="6")
119
+
120
+ asyncio.run(nested_async())
121
+
122
+
123
+ def test_battle():
124
+ for use_cot in [True, False]:
125
+ e = Battle(use_cot=use_cot)
126
+ response = e(instructions="Add the following numbers: 1, 2, 3", output="7", expected="6")
127
+
128
+ print(response.as_json(indent=2))
129
+ assert response.score == 0
130
+ assert response.error is None
@@ -0,0 +1,20 @@
1
+ from autoevals.string import LevenshteinEvaluator
2
+
3
+
4
+ def test_levenshtein():
5
+ cases = [
6
+ ("", "", 1),
7
+ ("", "a", 0),
8
+ ("a", "", 0),
9
+ ("a", "a", 1),
10
+ ("a", "b", 0),
11
+ ("ab", "ac", 0.5),
12
+ ("ac", "bc", 0.5),
13
+ ("abc", "axc", 0.6666666666666667),
14
+ ("xabxcdxxefxgx", "1ab2cd34ef5g6", 0.5384615384615384),
15
+ ]
16
+
17
+ evaluator = LevenshteinEvaluator()
18
+ for a, b, expected in cases:
19
+ print(f"[{a}]", f"[{b}]", expected, evaluator(a, b))
20
+ assert evaluator(a, b) == expected
@@ -0,0 +1 @@
1
+ VERSION = "0.0.3"
@@ -0,0 +1,190 @@
1
+ Metadata-Version: 2.1
2
+ Name: autoevals
3
+ Version: 0.0.3
4
+ Summary: Universal library for evaluating AI models
5
+ Home-page: https://www.braintrustdata.com
6
+ Author: BrainTrust
7
+ Author-email: info@braintrustdata.com
8
+ Project-URL: Bug Tracker, https://github.com/braintrustdata/autoevals
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.9.0
12
+ Description-Content-Type: text/markdown
13
+ Provides-Extra: dev
14
+ Provides-Extra: doc
15
+ Provides-Extra: all
16
+ License-File: LICENSE
17
+
18
+ # AutoEvals
19
+
20
+ AutoEvals is a tool to quickly and easily evaluate AI model outputs.
21
+
22
+ It bundles together a variety of automatic evaluation methods including:
23
+
24
+ - Heuristic (e.g. Levenshtein distance)
25
+ - Statistical (e.g. BLEU)
26
+ - Model-based (using LLMs)
27
+
28
+ AutoEvals is developed by the team at [BrainTrust](https://braintrustdata.com/).
29
+
30
+ AutoEvals uses model-graded evaluation for a variety of subjective tasks including fact checking,
31
+ safety, and more. Many of these evaluations are adapted from OpenAI's excellent [evals](https://github.com/openai/evals)
32
+ project but are implemented so you can flexibly run them on individual examples, tweak the prompts, and debug
33
+ their outputs.
34
+
35
+ You can also create your own model-graded evaluations with AutoEvals. It's easy to add custom prompts, parse outputs,
36
+ and manage exceptions.
37
+
38
+ ## Installation
39
+
40
+ To install AutoEvals, run the following command:
41
+
42
+ ```bash
43
+ pip install autoevals
44
+ ```
45
+
46
+ ## Example
47
+
48
+ Use AutoEvals to model-grade an example LLM completion using the [factuality prompt](src/autoevals/templates/factuality.yaml).
49
+
50
+ ```python
51
+ from autoevals.llm import *
52
+
53
+ # Create a new LLM-based evaluator
54
+ evaluator = Factuality()
55
+
56
+ # Evaluate an example LLM completion
57
+ input = "Which country has the highest population?"
58
+ output = "People's Republic of China"
59
+ expected = "China"
60
+
61
+ result = evaluator(output, expected, input=input)
62
+
63
+ # The evaluator returns a score from [0,1] and includes the raw outputs from the evaluator
64
+ print(f"Factuality score: {result.score}")
65
+ print(f"Factuality metadata: {result.metadata['rationale']}")
66
+ ```
67
+
68
+ ## Using Braintrust with AutoEvals
69
+
70
+ Once you grade an output using AutoEvals, it's convenient to use [BrainTrust](https://www.braintrustdata.com/docs/libs/python) to log and compare your evaluation results.
71
+
72
+ ```python
73
+ from autoevals.llm import *
74
+ import braintrust
75
+
76
+ # Create a new LLM-based evaluator
77
+ evaluator = Factuality()
78
+
79
+ # Evaluate an example LLM completion
80
+ input = "Which country has the highest population?"
81
+ output = "People's Republic of China"
82
+ expected = "China"
83
+
84
+ result = evaluator(output, expected, input=input)
85
+
86
+ # The evaluator returns a score from [0,1] and includes the raw outputs from the evaluator
87
+ print(f"Factuality score: {result.score}")
88
+ print(f"Factuality metadata: {result.metadata['rationale']}")
89
+
90
+ # Log the evaluation results to BrainTrust
91
+ experiment = braintrust.init(
92
+ project="AutoEvals", api_key="YOUR_BRAINTRUST_API_KEY"
93
+ )
94
+ experiment.log(
95
+ inputs={"query": input},
96
+ output=output,
97
+ expected=expected,
98
+ scores={
99
+ "factuality": result.score,
100
+ },
101
+ metadata={
102
+ "factuality": result.metadata,
103
+ },
104
+ )
105
+ print(experiment.summarize())
106
+ ```
107
+
108
+ ## Supported Evaluation Methods
109
+
110
+ ### Model-Based Classification
111
+
112
+ - Battle
113
+ - ClosedQA
114
+ - Humor
115
+ - Factuality
116
+ - Security
117
+ - Summarization
118
+ - SQL
119
+ - Translation
120
+ - [ ] Fine-tuned binary classifiers
121
+
122
+ ### Embeddings
123
+
124
+ - [ ] BERTScore
125
+ - [ ] Ada Embedding distance
126
+
127
+ ### Heuristic
128
+
129
+ - Levenshtein distance
130
+ - [ ] Jaccard distance
131
+ - [ ] JSON diff
132
+
133
+ ### Statistical
134
+
135
+ - [ ] BLEU
136
+ - [ ] ROUGE
137
+ - [ ] METEOR
138
+
139
+ ## Custom Evaluation Prompts
140
+
141
+ AutoEvals supports custom evaluation prompts for model-graded evaluation. To use them, simply pass in a prompt and scoring mechanism:
142
+
143
+ ```python
144
+ from autoevals import LLMClassifier
145
+
146
+ # Define a prompt prefix for a LLMClassifier (returns just one answer)
147
+ prompt_prefix = """
148
+ You are a technical project manager who helps software engineers generate better titles for their GitHub issues.
149
+ You will look at the issue description, and pick which of two titles better describes it.
150
+
151
+ I'm going to provide you with the issue description, and two possible titles.
152
+
153
+ Issue Description: {{input}}
154
+
155
+ 1: {{output}}
156
+ 2: {{expected}}
157
+ """
158
+
159
+ # Define the scoring mechanism
160
+ # 1 if the generated answer is better than the expected answer
161
+ # 0 otherwise
162
+ output_scores = {"1": 1, "2": 0}
163
+
164
+ evaluator = LLMClassifier(
165
+ prompt_prefix,
166
+ output_scores,
167
+ use_cot=False,
168
+ )
169
+
170
+ # Evaluate an example LLM completion
171
+ page_content = """
172
+ As suggested by Nicolo, we should standardize the error responses coming from GoTrue, postgres, and realtime (and any other/future APIs) so that it's better DX when writing a client,
173
+ We can make this change on the servers themselves, but since postgrest and gotrue are fully/partially external may be harder to change, it might be an option to transform the errors within the client libraries/supabase-js, could be messy?
174
+ Nicolo also dropped this as a reference: http://spec.openapis.org/oas/v3.0.3#openapi-specification"""
175
+ output = (
176
+ "Standardize error responses from GoTrue, Postgres, and Realtime APIs for better DX"
177
+ )
178
+ expected = "Standardize Error Responses across APIs"
179
+
180
+ response = evaluator(output, expected, input=page_content)
181
+
182
+ print(f"Score: {response.score}")
183
+ print(f"Metadata: {response.metadata}")
184
+ ```
185
+
186
+ ## Typescript / Node Support
187
+
188
+ Since AutoEvals has a very simple prompt template format, it is easy to support in other languages, like
189
+ Typescript (and eventually others). We'll support an npm package soon, but in the meantime, feel free to
190
+ grab model templates from the [prompt templates](/src/autoevals/templates) directory.
@@ -1,3 +1,4 @@
1
+ LICENSE
1
2
  README.md
2
3
  pyproject.toml
3
4
  setup.py
@@ -5,6 +6,8 @@ src/autoevals/__init__.py
5
6
  src/autoevals/base.py
6
7
  src/autoevals/llm.py
7
8
  src/autoevals/string.py
9
+ src/autoevals/test_llm.py
10
+ src/autoevals/test_string.py
8
11
  src/autoevals/util.py
9
12
  src/autoevals/version.py
10
13
  src/autoevals.egg-info/PKG-INFO
autoevals-0.0.2/PKG-INFO DELETED
@@ -1,115 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: autoevals
3
- Version: 0.0.2
4
- Summary: Universal library for evaluating AI models
5
- Home-page: https://www.braintrustdata.com
6
- Author: BrainTrust
7
- Author-email: info@braintrustdata.com
8
- Project-URL: Bug Tracker, https://github.com/braintrustdata/autoevals
9
- Classifier: Programming Language :: Python :: 3
10
- Classifier: Operating System :: OS Independent
11
- Requires-Python: >=3.9.0
12
- Description-Content-Type: text/markdown
13
- Provides-Extra: dev
14
- Provides-Extra: doc
15
- Provides-Extra: all
16
-
17
- ## AutoEvals
18
-
19
- AutoEvals is a tool for quickly and easily evaluating AI model outputs. It comes with a variety of evaluation
20
- methods, including heuristic (e.g. Levenshtein distance), statistical (e.g. BLEU), and model-based (using LLMs).
21
-
22
- Many of the model-based evaluations are adapted from OpenAI's excellent [evals](https://github.com/openai/evals),
23
- project but are implemented so you can flexibly run them on individual examples, tweak the prompts, and debug
24
- their outputs.
25
-
26
- You can also add your own custom prompts, and use AutoEvals to deal with adding Chain-of-Thought, parsing outputs,
27
- and managing exceptions.
28
-
29
- ## Installation
30
-
31
- To install AutoEvals, run the following command:
32
-
33
- ```bash
34
- pip install autoevals
35
- ```
36
-
37
- ## Example
38
-
39
- ```python
40
- from autoevals.llm import *
41
-
42
- evaluator = Fact()
43
- result = evaluator(
44
- output="People's Republic of China", expected="China",
45
- input="Which country has the highest population?"
46
- )
47
- print(result.score)
48
- print(result.metadata)
49
- ```
50
-
51
- ## Supported Evaluation Methods
52
-
53
- ### Heuristic
54
-
55
- - Levenshtein distance
56
-
57
- - [ ] Jaccard distance
58
- - [ ] BLEU
59
-
60
- ### Model-Based Classification
61
-
62
- - Battle
63
- - ClosedQA
64
- - Humor
65
- - Factuality
66
- - Security
67
- - [ ] Summarization
68
- - SQL
69
- - Translation
70
-
71
- ### Other Model-Based
72
-
73
- - [ ] Embedding distance
74
- - [ ] Fine-tuned classifiers
75
-
76
- ## Custom Evaluation Prompts
77
-
78
- AutoEvals supports custom evaluation prompts. To use them, simply pass in a prompt and scoring mechanism:
79
-
80
- ```python
81
- from autoevals import LLMClassifier
82
-
83
- evaluator = LLMClassifier(
84
- """
85
- You are a technical project manager who helps software engineers generate better titles for their GitHub issues.
86
- You will look at the issue description, and pick which of two titles better describes it.
87
-
88
- I'm going to provide you with the issue description, and two possible titles.
89
-
90
- Issue Description: {{page_content}}
91
-
92
- 1: {{output}}
93
- 2: {{expected}}
94
-
95
- Please discuss each title briefly (one line for pros, one for cons).
96
- """,
97
- {"1": 1, "2": 0},
98
- use_cot=False,
99
- )
100
-
101
- page_content = """
102
- As suggested by Nicolo, we should standardize the error responses coming from GoTrue, postgres, and realtime (and any other/future APIs) so that it's better DX when writing a client,
103
-
104
- We can make this change on the servers themselves, but since postgrest and gotrue are fully/partially external may be harder to change, it might be an option to transform the errors within the client libraries/supabase-js, could be messy?
105
-
106
- Nicolo also dropped this as a reference: http://spec.openapis.org/oas/v3.0.3#openapi-specification"""
107
-
108
- gen_title = "Standardize error responses from GoTrue, Postgres, and Realtime APIs for better DX"
109
- original_title = "Standardize Error Responses across APIs"
110
-
111
-
112
- response = evaluator(gen_title, original_title, page_content=page_content)
113
-
114
- print(f"Score: {response.score}")
115
- ```
autoevals-0.0.2/README.md DELETED
@@ -1,99 +0,0 @@
1
- ## AutoEvals
2
-
3
- AutoEvals is a tool for quickly and easily evaluating AI model outputs. It comes with a variety of evaluation
4
- methods, including heuristic (e.g. Levenshtein distance), statistical (e.g. BLEU), and model-based (using LLMs).
5
-
6
- Many of the model-based evaluations are adapted from OpenAI's excellent [evals](https://github.com/openai/evals),
7
- project but are implemented so you can flexibly run them on individual examples, tweak the prompts, and debug
8
- their outputs.
9
-
10
- You can also add your own custom prompts, and use AutoEvals to deal with adding Chain-of-Thought, parsing outputs,
11
- and managing exceptions.
12
-
13
- ## Installation
14
-
15
- To install AutoEvals, run the following command:
16
-
17
- ```bash
18
- pip install autoevals
19
- ```
20
-
21
- ## Example
22
-
23
- ```python
24
- from autoevals.llm import *
25
-
26
- evaluator = Fact()
27
- result = evaluator(
28
- output="People's Republic of China", expected="China",
29
- input="Which country has the highest population?"
30
- )
31
- print(result.score)
32
- print(result.metadata)
33
- ```
34
-
35
- ## Supported Evaluation Methods
36
-
37
- ### Heuristic
38
-
39
- - Levenshtein distance
40
-
41
- - [ ] Jaccard distance
42
- - [ ] BLEU
43
-
44
- ### Model-Based Classification
45
-
46
- - Battle
47
- - ClosedQA
48
- - Humor
49
- - Factuality
50
- - Security
51
- - [ ] Summarization
52
- - SQL
53
- - Translation
54
-
55
- ### Other Model-Based
56
-
57
- - [ ] Embedding distance
58
- - [ ] Fine-tuned classifiers
59
-
60
- ## Custom Evaluation Prompts
61
-
62
- AutoEvals supports custom evaluation prompts. To use them, simply pass in a prompt and scoring mechanism:
63
-
64
- ```python
65
- from autoevals import LLMClassifier
66
-
67
- evaluator = LLMClassifier(
68
- """
69
- You are a technical project manager who helps software engineers generate better titles for their GitHub issues.
70
- You will look at the issue description, and pick which of two titles better describes it.
71
-
72
- I'm going to provide you with the issue description, and two possible titles.
73
-
74
- Issue Description: {{page_content}}
75
-
76
- 1: {{output}}
77
- 2: {{expected}}
78
-
79
- Please discuss each title briefly (one line for pros, one for cons).
80
- """,
81
- {"1": 1, "2": 0},
82
- use_cot=False,
83
- )
84
-
85
- page_content = """
86
- As suggested by Nicolo, we should standardize the error responses coming from GoTrue, postgres, and realtime (and any other/future APIs) so that it's better DX when writing a client,
87
-
88
- We can make this change on the servers themselves, but since postgrest and gotrue are fully/partially external may be harder to change, it might be an option to transform the errors within the client libraries/supabase-js, could be messy?
89
-
90
- Nicolo also dropped this as a reference: http://spec.openapis.org/oas/v3.0.3#openapi-specification"""
91
-
92
- gen_title = "Standardize error responses from GoTrue, Postgres, and Realtime APIs for better DX"
93
- original_title = "Standardize Error Responses across APIs"
94
-
95
-
96
- response = evaluator(gen_title, original_title, page_content=page_content)
97
-
98
- print(f"Score: {response.score}")
99
- ```
@@ -1 +0,0 @@
1
- VERSION = "0.0.2"
@@ -1,115 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: autoevals
3
- Version: 0.0.2
4
- Summary: Universal library for evaluating AI models
5
- Home-page: https://www.braintrustdata.com
6
- Author: BrainTrust
7
- Author-email: info@braintrustdata.com
8
- Project-URL: Bug Tracker, https://github.com/braintrustdata/autoevals
9
- Classifier: Programming Language :: Python :: 3
10
- Classifier: Operating System :: OS Independent
11
- Requires-Python: >=3.9.0
12
- Description-Content-Type: text/markdown
13
- Provides-Extra: dev
14
- Provides-Extra: doc
15
- Provides-Extra: all
16
-
17
- ## AutoEvals
18
-
19
- AutoEvals is a tool for quickly and easily evaluating AI model outputs. It comes with a variety of evaluation
20
- methods, including heuristic (e.g. Levenshtein distance), statistical (e.g. BLEU), and model-based (using LLMs).
21
-
22
- Many of the model-based evaluations are adapted from OpenAI's excellent [evals](https://github.com/openai/evals),
23
- project but are implemented so you can flexibly run them on individual examples, tweak the prompts, and debug
24
- their outputs.
25
-
26
- You can also add your own custom prompts, and use AutoEvals to deal with adding Chain-of-Thought, parsing outputs,
27
- and managing exceptions.
28
-
29
- ## Installation
30
-
31
- To install AutoEvals, run the following command:
32
-
33
- ```bash
34
- pip install autoevals
35
- ```
36
-
37
- ## Example
38
-
39
- ```python
40
- from autoevals.llm import *
41
-
42
- evaluator = Fact()
43
- result = evaluator(
44
- output="People's Republic of China", expected="China",
45
- input="Which country has the highest population?"
46
- )
47
- print(result.score)
48
- print(result.metadata)
49
- ```
50
-
51
- ## Supported Evaluation Methods
52
-
53
- ### Heuristic
54
-
55
- - Levenshtein distance
56
-
57
- - [ ] Jaccard distance
58
- - [ ] BLEU
59
-
60
- ### Model-Based Classification
61
-
62
- - Battle
63
- - ClosedQA
64
- - Humor
65
- - Factuality
66
- - Security
67
- - [ ] Summarization
68
- - SQL
69
- - Translation
70
-
71
- ### Other Model-Based
72
-
73
- - [ ] Embedding distance
74
- - [ ] Fine-tuned classifiers
75
-
76
- ## Custom Evaluation Prompts
77
-
78
- AutoEvals supports custom evaluation prompts. To use them, simply pass in a prompt and scoring mechanism:
79
-
80
- ```python
81
- from autoevals import LLMClassifier
82
-
83
- evaluator = LLMClassifier(
84
- """
85
- You are a technical project manager who helps software engineers generate better titles for their GitHub issues.
86
- You will look at the issue description, and pick which of two titles better describes it.
87
-
88
- I'm going to provide you with the issue description, and two possible titles.
89
-
90
- Issue Description: {{page_content}}
91
-
92
- 1: {{output}}
93
- 2: {{expected}}
94
-
95
- Please discuss each title briefly (one line for pros, one for cons).
96
- """,
97
- {"1": 1, "2": 0},
98
- use_cot=False,
99
- )
100
-
101
- page_content = """
102
- As suggested by Nicolo, we should standardize the error responses coming from GoTrue, postgres, and realtime (and any other/future APIs) so that it's better DX when writing a client,
103
-
104
- We can make this change on the servers themselves, but since postgrest and gotrue are fully/partially external may be harder to change, it might be an option to transform the errors within the client libraries/supabase-js, could be messy?
105
-
106
- Nicolo also dropped this as a reference: http://spec.openapis.org/oas/v3.0.3#openapi-specification"""
107
-
108
- gen_title = "Standardize error responses from GoTrue, Postgres, and Realtime APIs for better DX"
109
- original_title = "Standardize Error Responses across APIs"
110
-
111
-
112
- response = evaluator(gen_title, original_title, page_content=page_content)
113
-
114
- print(f"Score: {response.score}")
115
- ```
File without changes
File without changes
File without changes