|
| 1 | +"""Base interface that all chains should implement.""" |
| 2 | +from abc import ABC, abstractmethod |
| 3 | +from typing import Any, Dict, List |
| 4 | + |
| 5 | + |
| 6 | +class Chain(ABC): |
| 7 | + """Base interface that all chains should implement.""" |
| 8 | + |
| 9 | + @property |
| 10 | + @abstractmethod |
| 11 | + def input_keys(self) -> List[str]: |
| 12 | + """Input keys this chain expects.""" |
| 13 | + |
| 14 | + @property |
| 15 | + @abstractmethod |
| 16 | + def output_keys(self) -> List[str]: |
| 17 | + """Output keys this chain expects.""" |
| 18 | + |
| 19 | + def _validate_inputs(self, inputs: Dict[str, str]) -> None: |
| 20 | + """Check that all inputs are present.""" |
| 21 | + missing_keys = set(self.input_keys).difference(inputs) |
| 22 | + if missing_keys: |
| 23 | + raise ValueError(f"Missing some input keys: {missing_keys}") |
| 24 | + |
| 25 | + def _validate_outputs(self, outputs: Dict[str, str]) -> None: |
| 26 | + if set(outputs) != set(self.output_keys): |
| 27 | + raise ValueError( |
| 28 | + f"Did not get output keys that were expected. " |
| 29 | + f"Got: {set(outputs)}. Expected: {set(self.output_keys)}." |
| 30 | + ) |
| 31 | + |
| 32 | + @abstractmethod |
| 33 | + def _run(self, inputs: Dict[str, str]) -> Dict[str, str]: |
| 34 | + """Run the logic of this chain and return the output.""" |
| 35 | + |
| 36 | + def __call__(self, inputs: Dict[str, Any]) -> Dict[str, str]: |
| 37 | + """Run the logic of this chain and add to output.""" |
| 38 | + self._validate_inputs(inputs) |
| 39 | + outputs = self._run(inputs) |
| 40 | + self._validate_outputs(outputs) |
| 41 | + return {**inputs, **outputs} |
0 commit comments