๐Ÿ’ป Exercise: Exercise: Parse a tool call

๐Ÿ“ Instructions

Write parse_tool_call(text). A tool request is two lines: 'TOOL: <name>' followed by 'ARGS: {json object}'. Return {'name': name, 'args': <parsed dict>}. If there is no ARGS: line, use {}. If the args JSON is malformed, use {}. Return None when there is no TOOL: line at all. This is native function calling, built by hand. Standard library only.

๐Ÿงช Initial Code / Tests

๐Ÿ“„ evaluate.py
from unittest import TestCase
from exercise import parse_tool_call


class Evaluate(TestCase):
    def test_parses_name_and_args(self):
        self.assertEqual(parse_tool_call('TOOL: add\nARGS: {"a": 2, "b": 3}'),
                         {'name': 'add', 'args': {'a': 2, 'b': 3}})

    def test_none_when_no_tool_line(self):
        self.assertIsNone(parse_tool_call('The answer is 5.'))

    def test_empty_args_when_no_args_line(self):
        self.assertEqual(parse_tool_call('TOOL: now')['args'], {})

    def test_malformed_json_degrades_to_empty(self):
        self.assertEqual(parse_tool_call('TOOL: add\nARGS: {not json}')['args'], {})

โœ… Solutions

๐Ÿ“„ exercise.py
import json
import re


def parse_tool_call(text):
    m_name = re.search(r'TOOL:\s*([A-Za-z0-9_\-]+)', text)
    if not m_name:
        return None
    m_args = re.search(r'ARGS:\s*(\{.*\})\s*$', text, re.DOTALL)
    args = {}
    if m_args:
        try:
            parsed = json.loads(m_args.group(1))
            args = parsed if isinstance(parsed, dict) else {}
        except json.JSONDecodeError:
            args = {}
    return {'name': m_name.group(1), 'args': args}