show me a simple way to implement a simple dsl (using python) for computed metrics on top of time-series database fields. metrics should ne able to be combined and we need to see the tree of computations and know which db fields go into the calculation of a computed metric.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a minimal but complete example that gives you
A tiny DSL to express computed metrics.
Automatic tracking of the computation tree (what depends on what).
A list of the raw database fields that finally feed the metric.
The whole thing is < 100 lines and has zero external dependencies.
python
from __future__ import annotations
from typing import Dict, List, Set, Any
import json
# ------------------------------------------------------------------
# 1. A tiny expression tree
# ------------------------------------------------------------------
class Expr:
"""Base class for every node in the computation tree."""
def __init__(self, *children: "Expr"):
self.children = list(children)
# Pretty print the tree
def tree(self, indent: int = 0) -> str:
prefix = " " * indent
name = self.__class__.__name__
if not self.children:
return f"{prefix}{name}: {self}"
lines = [f"{prefix}{name}"]
for c in self.children:
lines.append(c.tree(indent + 1))
return "\n".join(lines)
# Collect all raw field names used under this node
def raw_fields(self) -> Set[str]:
out = set()
for c in self.children:
out |= c.raw_fields()
return out
# Evaluate the expression given a dict of raw values
def eval(self, env: Dict[str, float]) -> float:
raise NotImplementedError
# ------------------------------------------------------------------
# 2. Leaf nodes
# ------------------------------------------------------------------
class Field(Expr):
"""A raw database column."""
def __init__(self, name: str):
super().__init__()
self.name = name
def __repr__(self):
return f"Field({self.name})"
def raw_fields(self) -> Set[str]:
return {self.name}
def eval(self, env: Dict[str, float]) -> float:
return env[self.name]
class Const(Expr):
"""A literal number."""
def __init__(self, value: float):
super().__init__()
self.value = value
def __repr__(self):
return str(self.value)
def raw_fields(self) -> Set[str]:
return set()
def eval(self, env: Dict[str, float]) -> float:
return self.value
# ------------------------------------------------------------------
# 3. Arithmetic combinators
# ------------------------------------------------------------------
class Add(Expr):
def eval(self, env: Dict[str, float]) -> float:
return self.children[0].eval(env) + self.children[1].eval(env)
class Sub(Expr):
def eval(self, env: Dict[str, float]) -> float:
return self.children[0].eval(env) - self.children[1].eval(env)
class Mul(Expr):
def eval(self, env: Dict[str, float]) -> float:
return self.children[0].eval(env) * self.children[1].eval(env)
class Div(Expr):
def eval(self, env: Dict[str, float]) -> float:
return self.children[0].eval(env) / self.children[1].eval(env)
# ------------------------------------------------------------------
# 4. Convenience builder functions (the actual DSL)
# ------------------------------------------------------------------
F = Field
C = Const
def add(a, b): return Add(a, b)
def sub(a, b): return Sub(a, b)
def mul(a, b): return Mul(a, b)
def div(a, b): return Div(a, b)
# ------------------------------------------------------------------
# 5. Example usage
# ------------------------------------------------------------------
if __name__ == "__main__":
# Define some metrics -------------------------------------------------
revenue = F("price") * F("quantity")
cost = F("cost_per_unit") * F("quantity")
profit = revenue - cost
profit_ratio = profit / revenue
# Inspect any metric --------------------------------------------------
for name, metric in [("revenue", revenue),
("profit", profit),
("profit_ratio", profit_ratio)]:
print(f"\n=== {name} ===")
print("Tree:")
print(metric.tree())
print("Raw fields:", sorted(metric.raw_fields()))
# Evaluate given a row from the TSDB ----------------------------------
row = {"price": 10, "quantity": 5, "cost_per_unit": 3}
print("\nEvaluation with", row)
print("profit_ratio =", profit_ratio.eval(row))
Running the file prints
code
=== revenue ===
Tree:
Mul
Field(price)
Field(quantity)
Raw fields: ['price', 'quantity']
=== profit ===
Tree:
Sub
Mul
Field(price)
Field(quantity)
Mul
Field(cost_per_unit)
Field(quantity)
Raw fields: ['cost_per_unit', 'price', 'quantity']
=== profit_ratio ===
Tree:
Div
Sub
Mul
Field(price)
Field(quantity)
Mul
Field(cost_per_unit)
Field(quantity)
Mul
Field(price)
Field(quantity)
Raw fields: ['cost_per_unit', 'price', 'quantity']
Evaluation with {'price': 10, 'quantity': 5, 'cost_per_unit': 3}
profit_ratio = 0.7
That’s it—no parsing, no external libraries, yet you can freely compose metrics and always know exactly which raw fields are required and how the calculation is structured.