Write dispatch(registry, name, args) where registry is a dict of name -> callable. On success return {'ok': True, 'output': <result>}. For an unknown tool return {'ok': False, 'error': <message containing 'unknown'>}. If the call raises TypeError (wrong or missing args) return {'ok': False, 'error': <message containing 'bad arguments'>}. Never raise -- always return a structured dict. Standard library only.
from unittest import TestCase
from exercise import dispatch
class Evaluate(TestCase):
def test_runs_known_tool(self):
reg = {'add': lambda a, b: a + b}
self.assertEqual(dispatch(reg, 'add', {'a': 2, 'b': 3}), {'ok': True, 'output': 5})
def test_unknown_tool_is_not_ok(self):
self.assertFalse(dispatch({}, 'ghost', {})['ok'])
def test_unknown_tool_error_mentions_unknown(self):
self.assertIn('unknown', dispatch({}, 'ghost', {})['error'])
def test_bad_arguments_handled(self):
reg = {'add': lambda a, b: a + b}
self.assertIn('bad arguments', dispatch(reg, 'add', {'a': 1})['error'])
def dispatch(registry, name, args):
if name not in registry:
return {'ok': False, 'error': "unknown tool '" + name + "'"}
try:
output = registry[name](**args)
except TypeError as exc:
return {'ok': False, 'error': 'bad arguments: ' + str(exc)}
return {'ok': True, 'output': output}