๐Ÿ’ป Exercise: Exercise: Format a structured log record

๐Ÿ“ Instructions

Write format_log_record(step, action, cost=0.0, cumulative=0.0) returning a flat dict with exactly these keys: step, action, cost_usd (rounded to 6 places), cumulative_cost_usd (rounded to 6 places), and ok (always True). Standard library only.

๐Ÿงช Initial Code / Tests

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


class Evaluate(TestCase):
    def test_has_exact_keys(self):
        rec = format_log_record(1, 'llm_call')
        self.assertEqual(set(rec), {'step', 'action', 'cost_usd', 'cumulative_cost_usd', 'ok'})

    def test_carries_step_and_action(self):
        rec = format_log_record(3, 'tool_call')
        self.assertEqual((rec['step'], rec['action']), (3, 'tool_call'))

    def test_rounds_cost(self):
        rec = format_log_record(1, 'x', cost=0.123456789)
        self.assertEqual(rec['cost_usd'], 0.123457)

    def test_ok_defaults_true(self):
        self.assertTrue(format_log_record(1, 'x')['ok'])

โœ… Solutions

๐Ÿ“„ exercise.py
def format_log_record(step, action, cost=0.0, cumulative=0.0):
    return {
        'step': step,
        'action': action,
        'cost_usd': round(cost, 6),
        'cumulative_cost_usd': round(cumulative, 6),
        'ok': True,
    }