You are porting a scikit-learn nearest-neighbor classification service to run on Modal.
The service fits a KNeighborsClassifier on the wine dataset once, then reuses the
fitted model to answer classification queries for multiple batches of samples.
The model is trained once on a fixed dataset; the trained model state should be initialized
once per container and reused across all prediction calls.
Current Implementation
The current workflow.py defines a single run_workflow(case) function that:
Loads the wine dataset and applies StandardScaler
Splits 75/25 train/test with random_state=0
Fits KNeighborsClassifier(n_neighbors=5) on the scaled training data
Uses case['random_state'] and case['n_samples'] to pick random test indices,
runs predict and predict_proba, and returns results
Your Task
Refactor this into a Modal service so that:
The scaler and KNN model are fitted exactly once when the container starts
A query method accepts a case dict and returns predictions, probabilities, and accuracy
The service can handle multiple independent case dicts efficiently
Input / Output
Input (case dict):
n_samples (int): number of test samples to query
random_state (int): seed for reproducible sample selection
Output (dict):
predictions (list of int): predicted class labels
probabilities (list of list of float): per-class probabilities, shape [n_samples, n_classes],
values rounded to 4 decimal places
accuracy (float): accuracy on the selected samples
Constraints
Use random_state=0 for the train/test split (test_size=0.25)
Use n_neighbors=5 for the classifier
All outputs must be JSON-serializable (convert numpy types to Python native types)
The model must not be re-fitted between query calls
Required solution interface
Write the solution in /app/solution/modal_app.py. Define a Modal application
object named app and expose a callable named run_case that accepts one case
dictionary and returns a JSON-serializable result matching the original
workflow.
Runtime file layout
The finalized task workspace is copied into /app when the sandbox starts.
Source files from environment/workspace are available at paths such as
/app/workflow.py, /app/original_workflow.py, /app/original.py, or other
task-specific filenames.
Capability contract
Expose the workflow as a single Modal remote function: define run_case as an @app.function so the harness can invoke it with run_case.remote(case).