|
| 1 | +"""Base class for an Openlayer model.""" |
| 2 | + |
| 3 | +import os |
| 4 | +import abc |
| 5 | +import json |
| 6 | +import time |
| 7 | +import inspect |
| 8 | +import argparse |
| 9 | +from typing import Any, Dict, Tuple |
| 10 | +from dataclasses import field, dataclass |
| 11 | + |
| 12 | +import pandas as pd |
| 13 | + |
| 14 | +from ..tracing import tracer |
| 15 | + |
| 16 | + |
| 17 | +@dataclass |
| 18 | +class RunReturn: |
| 19 | + """The return type of the `run` method in the Openlayer model.""" |
| 20 | + |
| 21 | + output: Any |
| 22 | + """The output of the model.""" |
| 23 | + |
| 24 | + other_fields: Dict[str, Any] = field(default_factory=dict) |
| 25 | + """Any other fields that you want to log.""" |
| 26 | + |
| 27 | + |
| 28 | +class OpenlayerModel(abc.ABC): |
| 29 | + """Interface for the Openlayer model. |
| 30 | +
|
| 31 | + Your model's class should inherit from this class and implement either: |
| 32 | + - the `run` method (which takes a single row of data as input and returns |
| 33 | + a `RunReturn` object) |
| 34 | + - `run_batch_from_df` method (which takes a pandas DataFrame as input and returns |
| 35 | + a tuple of a DataFrame and a config dict). |
| 36 | +
|
| 37 | + It is more conventional to implement the `run` method. |
| 38 | +
|
| 39 | + Refer to Openlayer's templates for examples of how to implement this class. |
| 40 | + """ |
| 41 | + |
| 42 | + def run_from_cli(self) -> None: |
| 43 | + """Run the model from the command line.""" |
| 44 | + parser = argparse.ArgumentParser(description="Run data through a model.") |
| 45 | + parser.add_argument( |
| 46 | + "--dataset-path", type=str, required=True, help="Path to the dataset" |
| 47 | + ) |
| 48 | + parser.add_argument( |
| 49 | + "--output-dir", |
| 50 | + type=str, |
| 51 | + required=False, |
| 52 | + help="Directory to dump the results in", |
| 53 | + ) |
| 54 | + |
| 55 | + # Parse the arguments |
| 56 | + args = parser.parse_args() |
| 57 | + |
| 58 | + return self.batch( |
| 59 | + dataset_path=args.dataset_path, |
| 60 | + output_dir=args.output_dir, |
| 61 | + ) |
| 62 | + |
| 63 | + def batch(self, dataset_path: str, output_dir: str) -> None: |
| 64 | + """Reads the dataset from a file and runs the model on it.""" |
| 65 | + # Load the dataset into a pandas DataFrame |
| 66 | + if dataset_path.endswith(".csv"): |
| 67 | + df = pd.read_csv(dataset_path) |
| 68 | + elif dataset_path.endswith(".json"): |
| 69 | + df = pd.read_json(dataset_path, orient="records") |
| 70 | + |
| 71 | + # Call the model's run_batch method, passing in the DataFrame |
| 72 | + output_df, config = self.run_batch_from_df(df) |
| 73 | + self.write_output_to_directory(output_df, config, output_dir) |
| 74 | + |
| 75 | + def run_batch_from_df(self, df: pd.DataFrame) -> Tuple[pd.DataFrame, dict]: |
| 76 | + """Function that runs the model and returns the result.""" |
| 77 | + # Ensure the 'output' column exists |
| 78 | + if "output" not in df.columns: |
| 79 | + df["output"] = None |
| 80 | + |
| 81 | + # Get the signature of the 'run' method |
| 82 | + run_signature = inspect.signature(self.run) |
| 83 | + |
| 84 | + for index, row in df.iterrows(): |
| 85 | + # Filter row_dict to only include keys that are valid parameters |
| 86 | + # for the 'run' method |
| 87 | + row_dict = row.to_dict() |
| 88 | + filtered_kwargs = { |
| 89 | + k: v for k, v in row_dict.items() if k in run_signature.parameters |
| 90 | + } |
| 91 | + |
| 92 | + # Call the run method with filtered kwargs |
| 93 | + output = self.run(**filtered_kwargs) |
| 94 | + |
| 95 | + df.at[index, "output"] = output.output |
| 96 | + |
| 97 | + for k, v in output.other_fields.items(): |
| 98 | + if k not in df.columns: |
| 99 | + df[k] = None |
| 100 | + df.at[index, k] = v |
| 101 | + |
| 102 | + trace = tracer.get_current_trace() |
| 103 | + if trace: |
| 104 | + processed_trace, _ = tracer.post_process_trace(trace_obj=trace) |
| 105 | + df.at[index, "steps"] = trace.to_dict() |
| 106 | + if "latency" in processed_trace: |
| 107 | + df.at[index, "latency"] = processed_trace["latency"] |
| 108 | + if "cost" in processed_trace: |
| 109 | + df.at[index, "cost"] = processed_trace["cost"] |
| 110 | + if "tokens" in processed_trace: |
| 111 | + df.at[index, "tokens"] = processed_trace["tokens"] |
| 112 | + |
| 113 | + config = { |
| 114 | + "outputColumnName": "output", |
| 115 | + "inputVariableNames": list(run_signature.parameters.keys()), |
| 116 | + "metadata": { |
| 117 | + "output_timestamp": time.time(), |
| 118 | + }, |
| 119 | + } |
| 120 | + |
| 121 | + if "latency" in df.columns: |
| 122 | + config["latencyColumnName"] = "latency" |
| 123 | + if "cost" in df.columns: |
| 124 | + config["costColumnName"] = "cost" |
| 125 | + if "tokens" in df.columns: |
| 126 | + config["numOfTokenColumnName"] = "tokens" |
| 127 | + |
| 128 | + return df, config |
| 129 | + |
| 130 | + def write_output_to_directory( |
| 131 | + self, |
| 132 | + output_df: pd.DataFrame, |
| 133 | + config: Dict[str, Any], |
| 134 | + output_dir: str, |
| 135 | + fmt: str = "json", |
| 136 | + ): |
| 137 | + """Writes the output DataFrame to a file in the specified directory based on the |
| 138 | + given format. |
| 139 | + """ |
| 140 | + os.makedirs( |
| 141 | + output_dir, exist_ok=True |
| 142 | + ) # Create the directory if it doesn't exist |
| 143 | + |
| 144 | + # Determine the filename based on the dataset name and format |
| 145 | + filename = f"dataset.{fmt}" |
| 146 | + output_path = os.path.join(output_dir, filename) |
| 147 | + |
| 148 | + # Write the config to a json file |
| 149 | + config_path = os.path.join(output_dir, "config.json") |
| 150 | + with open(config_path, "w", encoding="utf-8") as f: |
| 151 | + json.dump(config, f, indent=4) |
| 152 | + |
| 153 | + # Write the DataFrame to the file based on the specified format |
| 154 | + if fmt == "csv": |
| 155 | + output_df.to_csv(output_path, index=False) |
| 156 | + elif fmt == "json": |
| 157 | + output_df.to_json(output_path, orient="records", indent=4) |
| 158 | + else: |
| 159 | + raise ValueError("Unsupported format. Please choose 'csv' or 'json'.") |
| 160 | + |
| 161 | + print(f"Output written to {output_path}") |
| 162 | + |
| 163 | + @abc.abstractmethod |
| 164 | + def run(self, **kwargs) -> RunReturn: |
| 165 | + """Function that runs the model and returns the result.""" |
| 166 | + pass |
0 commit comments