Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion app/docs/dev.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# ArraySymbolicEqual

This evaluation function can take any level of nesting for "response" and "answer" fields, as comparison is done recursively (as long as both shapes are identical). Symbolic grading is done using the [SymbolicEqual](https://lambda-feedback.github.io/user-documentation/user_eval_function_docs/symbolicEqual/) function, called using the experimental EvaluationFunctionClient from the evaluation-function-utils library.
This evaluation function can take any level of nesting for "response" and "answer" fields, as comparison is done recursively (as long as both shapes are identical). Symbolic grading is done using the [SymbolicEqual](https://lambda-feedback.github.io/user-documentation/user_eval_function_docs/symbolicEqual/) function, called over HTTPS.

The full URL of the `symbolicEqual` function to call is read from the `SYMBOLIC_EQUAL_URL` environment variable (e.g. `https://<api-id>.execute-api.eu-west-2.amazonaws.com/default/symbolicEqual`), which must be set on the deployed function. No AWS credentials or IAM permissions are needed.

## Inputs
This compares cells using the `symbolicEqual` function. Please consult that function's documentation for details on it's allowable parameters, as the ones provided to this function are fed through as they are.
Expand Down
69 changes: 65 additions & 4 deletions app/evaluation.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,84 @@
import re
import json
import os
import urllib.error
import urllib.request

from evaluation_function_utils.client import EvaluationFunctionClient
from evaluation_function_utils.errors import EvaluationException

try:
from .shape import shape_feedback
except ImportError:
from shape import shape_feedback

client = EvaluationFunctionClient(env_path=".env")
# Full URL of the symbolicEqual function to call, e.g.
# https://<api-id>.execute-api.eu-west-2.amazonaws.com/default/symbolicEqual
SYMBOLIC_EQUAL_URL_ENV = "SYMBOLIC_EQUAL_URL"

# API Gateway HTTP APIs time out after 30 seconds.
REQUEST_TIMEOUT_SECONDS = 30


class EvaluationFunctionInvoker:
"""
Calls another deployed evaluation function over HTTPS, the same way any
other client does. No AWS credentials or IAM permissions are needed.
"""

def invoke(self, url, response, answer, params=None):
data = json.dumps({
"response": response,
"answer": answer,
"params": params or {},
}).encode("utf-8")
request = urllib.request.Request(
url,
data=data,
method="POST",
headers={"Content-Type": "application/json", "command": "eval"},
)

try:
with urllib.request.urlopen(
request, timeout=REQUEST_TIMEOUT_SECONDS) as res:
decoded_str = res.read().decode("utf-8")
except urllib.error.HTTPError as e:
raise RuntimeError(f"{url} returned HTTP {e.code}") from e
except urllib.error.URLError as e:
raise RuntimeError(f"Request to {url} failed: {e.reason}") from e

try:
decoded = json.loads(decoded_str)
except ValueError:
raise EvaluationException(
f"Response from {url} could not be parsed.",
raw_response=decoded_str)

# Re-raise evaluation errors as if the function was run locally.
if "error" in decoded:
raise EvaluationException(**decoded["error"])

if "result" in decoded:
return decoded["result"]

raise EvaluationException(
f"{url} did not return an error or a result.",
raw_response=decoded)


client = EvaluationFunctionInvoker()


def grade_single_cell(res, ans, params):
"""
Attempt to grade a single cell using the SymbolicEqual function,
fallback to a local version if the request fails
"""
url = os.getenv(SYMBOLIC_EQUAL_URL_ENV)
if not url:
raise RuntimeError(f"{SYMBOLIC_EQUAL_URL_ENV} is not set")

try:
return client.invoke('symbolicEqual', res, ans, params=params)
return client.invoke(url, res, ans, params=params)
except EvaluationException as e:
return e.error_dict

Expand Down
77 changes: 60 additions & 17 deletions app/evaluation_tests.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,64 @@
import io
import json
import os
import unittest
from unittest import mock

from evaluation_function_utils.client import MissingCredentials
try:
from . import evaluation
except ImportError:
import evaluation

evaluation_function = evaluation.evaluation_function

def import_evaluation():
try:
from . import evaluation
except ImportError:
import evaluation
return evaluation

URL = "https://gateway.example.com/default/symbolicEqual"

# The real client needs AWS credentials on creation. Without them, import
# with a mock client so the tests below (which mock the client) can still run.
try:
evaluation = import_evaluation()
except MissingCredentials:
with mock.patch("evaluation_function_utils.client.EvaluationFunctionClient"):
evaluation = import_evaluation()

evaluation_function = evaluation.evaluation_function
class TestEvaluationFunctionInvoker(unittest.TestCase):
"""Tests for calling another function over HTTPS."""

def call(self, body):
"""Invoke with a mocked HTTP response; returns (result, request)."""
res = mock.MagicMock()
res.read.return_value = json.dumps(body).encode("utf-8")
res.__enter__.return_value = res

with mock.patch.object(evaluation.urllib.request, "urlopen",
return_value=res) as urlopen:
result = evaluation.EvaluationFunctionInvoker().invoke(
URL, "a", "a", params={"x": 1})
return result, urlopen.call_args.args[0]

def test_returns_result(self):
result, request = self.call(
{"command": "eval", "result": {"is_correct": True}})

self.assertEqual(result, {"is_correct": True})
self.assertEqual(request.full_url, URL)
self.assertEqual(request.get_method(), "POST")
self.assertEqual(request.get_header("Command"), "eval")
self.assertEqual(json.loads(request.data), {
"response": "a", "answer": "a", "params": {"x": 1},
})

def test_error_raises_evaluation_exception(self):
with self.assertRaises(evaluation.EvaluationException) as ctx:
self.call({"error": {"message": "parse failed"}})
self.assertEqual(ctx.exception.message, "parse failed")

def test_http_error_raises(self):
error = evaluation.urllib.error.HTTPError(
URL, 500, "Internal Server Error", {}, io.BytesIO(b""))
with mock.patch.object(evaluation.urllib.request, "urlopen",
side_effect=error):
with self.assertRaises(RuntimeError):
evaluation.EvaluationFunctionInvoker().invoke(URL, "a", "a")

def test_missing_url_raises(self):
with mock.patch.dict(os.environ, {}, clear=True):
with self.assertRaises(RuntimeError):
evaluation.grade_single_cell("a", "a", {})


class TestEvaluationFunction(unittest.TestCase):
Expand All @@ -47,6 +85,11 @@ def setUp(self):
self.client = patcher.start()
self.addCleanup(patcher.stop)

env = mock.patch.dict(os.environ,
{evaluation.SYMBOLIC_EQUAL_URL_ENV: URL})
env.start()
self.addCleanup(env.stop)

def assert_size_feedback(self, response, answer, feedback):
result = evaluation_function(response, answer, {})

Expand Down Expand Up @@ -111,8 +154,8 @@ def test_answer_not_list(self):
evaluation_function(["a"], "a", {})

"""
NOTE: This function was converted to use the experimental
EvaluationFunctionClient which doesn't support testing yet.
NOTE: These tests call the deployed symbolicEqual function, so they
can't run in CI without AWS access.

def test_vector_incorrect(self):
response = ["a + b - a", "2 + c", "d"]
Expand Down
2 changes: 1 addition & 1 deletion app/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
numpy
evaluation-function-utils
evaluation-function-utils
Loading