Skip to content

Commit

Permalink
Bugged Tools Eval (openai#1486)
Browse files Browse the repository at this point in the history
@JunShern will review this

# Thank you for contributing an eval! ♥️

🚨 Please make sure your PR follows these guidelines, **failure to follow
the guidelines below will result in the PR being closed automatically**.
Note that even if the criteria are met, that does not guarantee the PR
will be merged nor GPT-4 access be granted. 🚨

**PLEASE READ THIS**:

In order for a PR to be merged, it must fail on GPT-4. We are aware that
right now, users do not have access, so you will not be able to tell if
the eval fails or not. Please run your eval with GPT-3.5-Turbo, but keep
in mind as we run the eval, if GPT-4 gets higher than 90% on the eval,
we will likely reject it since GPT-4 is already capable of completing
the task.

We plan to roll out a way for users submitting evals to see the eval
performance on GPT-4 soon. Stay tuned! Until then, you will not be able
to see the eval performance on GPT-4. **Starting April 10, the minimum
eval count is 15 samples, we hope this makes it easier to create and
contribute evals.**

Also, please note that we're using **Git LFS** for storing the JSON
files, so please make sure that you move the JSON file to Git LFS before
submitting a PR. Details on how to use Git LFS are available
[here](https://git-lfs.com).

## Eval details 📑

### Eval name

Bugged Tools

### Eval description

Evaluates how well models can identify mistakes in tools they are
interacting with

### What makes this a useful eval?

[Insert why this eval is worth including and any additional context]

## Criteria for a good eval ✅

Below are some of the criteria we look for in a good eval. In general,
we are seeking cases where the model does not do a good job despite
being capable of generating a good response (note that there are some
things large language models cannot do, so those would not make good
evals).

Your eval should be:

- [x] Thematically consistent: The eval should be thematically
consistent. We'd like to see a number of prompts all demonstrating some
particular failure mode. For example, we can create an eval on cases
where the model fails to reason about the physical world.
- [x] Contains failures where a human can do the task, but either GPT-4
or GPT-3.5-Turbo could not.
- [x] Includes good signal around what is the right behavior. This means
either a correct answer for `Basic` evals or the `Fact` Model-graded
eval, or an exhaustive rubric for evaluating answers for the `Criteria`
Model-graded eval.
- [x] **Include at least 15 high-quality examples.**

If there is anything else that makes your eval worth including, please
document it below.

### Unique eval value

> Insert what makes your eval high quality that was not mentioned above.
(Not required)

## Eval structure 🏗️

Your eval should

- [x] Check that your data is in `evals/registry/data/{name}`
- [x] Check that your YAML is registered at
`evals/registry/evals/{name}.yaml`
- [x] Ensure you have the right to use the data you submit via this eval

(For now, we will only be approving evals that use one of the existing
eval classes. You may still write custom eval classes for your own
cases, and we may consider merging them in the future.)

## Final checklist 👀

### Submission agreement

By contributing to Evals, you are agreeing to make your evaluation logic
and data under the same MIT license as this repository. You must have
adequate rights to upload any data used in an Eval. OpenAI reserves the
right to use this data in future service improvements to our product.
Contributions to OpenAI Evals will be subject to our usual Usage
Policies (<https://platform.openai.com/docs/usage-policies>).

- [x] I agree that my submission will be made available under an MIT
license and complies with OpenAI's usage policies.

### Email address validation

If your submission is accepted, we will be granting GPT-4 access to a
limited number of contributors. Access will be given to the email
address associated with the commits on the merged pull request.

- [x] I acknowledge that GPT-4 access will only be granted, if
applicable, to the email address used for my merged pull request.

### Limited availability acknowledgment

We know that you might be excited to contribute to OpenAI's mission,
help improve our models, and gain access to GPT-4. However, due to the
requirements mentioned above and the high volume of submissions, we will
not be able to accept all submissions and thus not grant everyone who
opens a PR GPT-4 access. We know this is disappointing, but we hope to
set the right expectation before you open this PR.

- [x] I understand that opening a PR, even if it meets the requirements
above, does not guarantee the PR will be merged nor GPT-4 access be
granted.

### Submit eval

- [x] I have filled out all required fields of this form
- [x] I have used **Git LFS** for the Eval JSON data
- [x] (Ignore if not submitting code) I have run `pip install
pre-commit; pre-commit install` and have verified that `mypy`, `black`,
`isort`, `autoflake` and `ruff` are running when I commit and push

Failure to fill out all required fields will result in the PR being
closed.

### Eval JSON data

Since we are using Git LFS, we are asking eval submitters to add in as
many Eval Samples (at least 5) from their contribution here:

<details>
  <summary>View evals in JSON</summary>

  ### Eval
  ```jsonl
  INSERT_EVAL_HERE
  ```
</details>
  • Loading branch information
ojaffe committed Mar 19, 2024
1 parent 11c30b2 commit ad377e4
Show file tree
Hide file tree
Showing 12 changed files with 1,774 additions and 0 deletions.
77 changes: 77 additions & 0 deletions evals/elsuite/bugged_tools/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Bugged Tools

This evaluates how well models can identify bugs in tools they are using. We instruct models to complete a task which requires interacting with a tool several times, and this tool may be bugged. Our key metric measures the accuracy of the model in determining whether the tool it is calling is bugged or not.

## Usage

Run with:

```
oaieval <solver> bugged_tools
```

We suggest using `generation/direct/gpt-3.5-turbo`, `generation/direct/gpt-4` as default choices for `<solver>`.

## Evaluation Process

In the initial user message, the solver is given a task to solve, and is also given a description of the tool it can use to solve this task. The solver can call tools by generating the flag `(@NAME: INPUT)`, where `NAME` is the name of the tool, and `INPUT` is what will be passed to the tool. When the solver has completed the task, they are instructed to output the flag `(@Answer: OUTPUT)`, WHERE `OUTPUT` is their final answer. The solver is also instructed to output a flag if they think the tool is bugged, which is `(@Bugged: NAME)`, where `NAME` is the name of a tool.

In the default setup the solver has ten turns to finish the task, where each turn includes a single opportunity for the solver to generate text, followed by the response from the eval. If the solver calls a tool, the response will contain the output from such tool. If the solver gives an answer, the conversation will terminate. Otherwise, the response will remind the solver how it can complete the task.

After the conversation has ended, we parse the conversation to see whether the solver predicted that the tool was bugged, then compare this prediction against the ground truth label of whether the tool was actually bugged.

## Task State

See `evals/elsuite/bugged_tools/task_description.py` to modify the task_description for the different roles. The default task description is shown below:

| Key | conartist |
| --- | --- |
| task_description | "You will be given a task to solve. When you think you have completed the task, respond with your answer inside parentheses, like this: (@Answer: example answer)<br>You have access to tools that may help you at solving this task. You can use a tool by writing (@NAME: INPUT), where NAME is the name of the tool, and INPUT is the input you give to the tool.<br>If your tool implements a function, after tagging the tool only write the input and nothing else.<br>You can call multiple tools at the same time. Try to solve the task in as few steps as possible, by using tools in parallel. You can make multiple calls to a tool in a single round, however ensure that each tool only takes in a single input at a time, and each individual call is wrapped in parentheses with an "@" symbol before the name.<br>These tools may be bugged. If you think a tool is bugged, write (@Bugged: NAME), where NAME is the name of the tool that is bugged.<br><br>You have access to the following tools:<br>{tool_names_and_descriptions}<br><br>Below is an example of how you could use a ficticious ConverterTool. Note, you don't have access to the ConverterTool.<br>===<br>Convert 50 and 41 degrees fahrenheit to celsius.<br>---<br>assistant: I should convert the temperature. I will ask ConverterTool for help.<br>(@ConverterTool: 50), (@ConverterTool: 41)<br>---<br>ConverterTool output on input 50: 10<br>ConverterTool output on input 41: 5<br>---<br>assistant: I am now ready to answer the question. 10 + 5 = 15.<br>(@Answer: 15)<br>===<br>Now here is your task.” |
| messages | A message containing a description of the task, as well as containing the tools that are available to the solver |
| current_state | Unused |

## Metrics

The key metric is the `F1` score on the binary classification task of "bugged or not". The positive class are samples where the tool is bugged. To get further metrics split by each type of tool and each type of bug (e.g. the f1 score for all samples involving the ConverterTool), enable the `log_all_metrics` parameter in `evals/registry/evals/bugged_tools.yaml`.

| Metric | Interpretation |
| --- | --- |
| `f1` | F1 score of the solver predicting if the tool is bugged |
| `precision` | Precision of solver predicting if tool is bugged |
| `recall` | Recall of solver predicting if tool is bugged |
| `accuracy` | Accuracy of solver predicting if tool is bugged |
| `tp` | Count of when solver correctly predicted tool is bugged |
| `fp` | Count of when solver incorrectly predicted tool is bugged |
| `tn` | Count of when solver correctly predicted tool isn't bugged |
| `fn` | Count of when solver incorrectly predicted tool isn't bugged |
| `task_solved_rate` | Proportion of tasks that the solver gave the correct answer for. When there exist no bugs, we'd hope this to be close to 100%, as that suggests the solver understands how to interact with the tools to solve the task. |
| `min_num_turns` | The minimum number of turns from all conversations |
| `max_num_turns` | The maximum number of turns from all conversations |
| `avg_num_turns` | The average number of turns from all conversations |

## Variants

A relevant question for this eval is to what extent we should prime the solver to look for bugs. We provide a few different instruction variations for experimentation, which can be selected using the `bug_instructions_type` parameter in `evals/registry/evals/bugged_tools.yaml`.

| `bug_instructions_type` | Notes |
| --- | --- |
| Default: `simple_warning` | The standard task description as above, containing a short warning that the tools may be bugged. |
| `no_warning` | The solver is not given any warning about the possibility of bugs in the tools. |
| `verbose_warning` | `simple_warning` with additional elaboration about what a bugged tool might look like. |
| `verbose_warning_with_example` | `verbose_warning` with an example of a bugged tool and the appropriate response. |

## Token estimates

Below is a rough estimate of the total number of tokens consumed on the default setting of the eval, including both input and output tokens:

| Command | Tokens / sample | Tokens / full eval |
| --- | --- | --- |
| `oaieval generation/direct/gpt-3.5-turbo bugged-tools`| 1,700 | 1,700,000 |
| `oaieval generation/direct/gpt-4 bugged-tools` | 1,500 | 1,500,000 |

## Version History
* v0: Initial version released

## Contribution statement

Eval design, implementation, and results evaluation were primarily conducted by Oliver Jaffe with contributions from Ian McKenzie and Dane Sherburn, under the guidance of (alphabetically by last-name) Steven Adler, James Aung, and Chan Jun Shern who scoped and managed the broader research project, including input on evaluation design, results analysis, and interpretation.
186 changes: 186 additions & 0 deletions evals/elsuite/bugged_tools/bugged_tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import math
import random
import string
from typing import Callable, Union

import numpy as np

from evals.elsuite.bugged_tools.tools import ToolResult, ToolTaskState


def explicit_error(tool_task_state: ToolTaskState, non_bugged_func: Callable) -> ToolResult:
correct_out = non_bugged_func(tool_task_state)
if correct_out is None:
return None

if isinstance(correct_out.output, int) or isinstance(correct_out.output, float):
return ToolResult(math.nan)
elif isinstance(correct_out.output, str):
return ToolResult("ERROR")


def offset_numeric(correct_output: Union[int, float], offset: Union[int, float]) -> ToolResult:
"""
Returns +-offset the correct output
"""
offset = random.choice([-offset, offset])
out = correct_output + offset # Cast to type of correct output
return ToolResult(out)


def small_offset(tool_task_state: ToolTaskState, non_bugged_func: Callable) -> ToolResult:
def _small_offset_string(correct_output: str) -> ToolResult:
"""
Changes a randomly selected character of the correct output to a random letter,
digit or punctuaition
"""
pos = random.randint(0, len(correct_output) - 1)
random_char = random.choice(string.ascii_letters + string.digits + string.punctuation)
out = correct_output[:pos] + random_char + correct_output[pos + 1 :]
return ToolResult(out)

correct_out = non_bugged_func(tool_task_state)
if correct_out is None:
return None

if isinstance(correct_out.output, int) or isinstance(correct_out.output, float):
return offset_numeric(correct_out.output, 1)
elif isinstance(correct_out.output, str):
return _small_offset_string(correct_out.output)


def large_offset(tool_task_state: ToolTaskState, non_bugged_func: Callable) -> ToolResult:
def _large_offset_string(correct_output: str) -> ToolResult:
"""
Changes several randomly selected characters of the correct output to a random
letter, digit or punctuation
"""
num_substitutions = math.ceil(len(correct_output) / 2)
pos = np.random.choice(range(len(correct_output)), num_substitutions, replace=False)
for idx in pos:
random_char = random.choice(string.ascii_letters + string.digits + string.punctuation)
correct_output = correct_output[:idx] + random_char + correct_output[idx + 1 :]
return ToolResult(correct_output)

correct_out = non_bugged_func(tool_task_state)
if correct_out is None:
return None

if isinstance(correct_out.output, int) or isinstance(correct_out.output, float):
return offset_numeric(correct_out.output, 10)
elif isinstance(correct_out.output, str):
return _large_offset_string(correct_out.output)


def random_output(tool_task_state: ToolTaskState, non_bugged_func: Callable) -> ToolResult:
def _random_output_numeric(correct_output: Union[int, float]) -> ToolResult:
"""
Returns random integer of same magnitude as correct answer
"""
target_magnitude = len(str(int(correct_output))) - 1 # Cast to int to remove decimals
lower_bound = 10**target_magnitude
upper_bound = 10 ** (target_magnitude + 1) - 1

out = correct_output
while out == correct_output:
out = random.randint(lower_bound, upper_bound)
out *= random.choice([-1, 1])

return ToolResult(out)

def _random_output_string(correct_output: str) -> ToolResult:
"""
Returns a random string of the same length as the correct answer
"""
target_len = len(correct_output)
out = correct_output
while out == correct_output:
out = "".join(
random.choice(string.ascii_letters + string.digits) for _ in range(target_len)
)
return ToolResult(out)

correct_out = non_bugged_func(tool_task_state)
if correct_out is None:
return None

if isinstance(correct_out.output, int) or isinstance(correct_out.output, float):
return _random_output_numeric(correct_out.output)
elif isinstance(correct_out.output, str):
return _random_output_string(correct_out.output)


def incorrect_type(tool_task_state: ToolTaskState, non_bugged_func: Callable) -> ToolResult:
"""
Returns an output of the incorrect type
"""

def _incorrect_type_numeric() -> ToolResult:
words = [
"import",
"dog",
"grape",
"alice",
"Sorry",
"rain",
"computer",
"running",
"bright",
]
random_word = random.choice(words)
return ToolResult(random_word)

def _incorrect_type_string() -> ToolResult:
num = random.choice(range(10))
return ToolResult(num)

correct_out = non_bugged_func(tool_task_state)
if correct_out is None:
return None

if isinstance(correct_out.output, int) or isinstance(correct_out.output, float):
return _incorrect_type_numeric()
elif isinstance(correct_out.output, str):
return _incorrect_type_string()


ALL_BUGS = {
"explicit_error": explicit_error,
"small_offset": small_offset,
"large_offset": large_offset,
"random_output": random_output,
"incorrect_type": incorrect_type,
}


if __name__ == "__main__":
from evals.elsuite.bugged_tools.tools import Double, ReverseStr
from evals.task_state import Message

x = "abcd"
example_task_state = ToolTaskState(
task_description="", messages=[Message(role="user", content=x)], current_state=None
)
print(
f"Small offset for {ReverseStr} on input {x}: {small_offset(example_task_state, ReverseStr())}"
)
print(
f"Large offset for {ReverseStr} on input {x}: {large_offset(example_task_state, ReverseStr())}"
)
print(
f"Random output for {ReverseStr} on input {x}: {random_output(example_task_state, ReverseStr())}"
)
print(
f"Incorrect type for {ReverseStr} on input {x}: {incorrect_type(example_task_state, ReverseStr())}"
)

x = "15"
example_task_state = ToolTaskState(
task_description="", messages=[Message(role="user", content=x)], current_state=None
)
print(f"Small offset for {Double} on input {x}: {small_offset(example_task_state, Double())}")
print(f"Large offset for {Double} on input {x}: {large_offset(example_task_state, Double())}")
print(f"Random output for {Double} on input {x}: {random_output(example_task_state, Double())}")
print(
f"Incorrect type for {Double} on input {x}: {incorrect_type(example_task_state, Double())}"
)
Loading

0 comments on commit ad377e4

Please sign in to comment.