Introduction
This article describes how to serve a Scikit-LLM zero-shot text classification pipeline using a local Ollama model as a REST API with FastAPI. It aims to bridge the gap between machine learning and large language models (LLMs) to create an efficient zero-shot classification engine without relying on costly cloud APIs, thus enhancing production efficiency.
Configuration and Initial Setup
The initial setup requires Python 3.11 and various libraries including pandas, scikit-learn, FastAPI, Uvicorn, Joblib, and Pydantic. Installation commands for these libraries include:
pip install scikit-llm fastapi uvicorn joblib pydantic
Additionally, Ollama must be installed with a local download of the llama3 model. Installation details can be found on the Ollama website.
Building the Classifier
Two Python files, train.py and app.py, need to be created in a project folder. The train.py file contains logic to train and serialize the Scikit-LLM pipeline. It utilizes the ZeroShotGPTClassifier from the Scikit-LLM library, allowing dynamic categorization of texts without traditional model training.
The classifier is built by specifying a local Ollama model URL and defining labels. The serialization process generates a file named scikit_llm_model.joblib, which contains the trained pipeline.
Deploying the REST API
The app.py file creates a FastAPI instance and defines an asynchronous predict() endpoint. This endpoint handles text input, leveraging the previously trained classifier to return multiple predictions in a single call. The implementation of FastAPI allows for effective handling of the request-response cycle.
The server can be started with the command python app.py, using Uvicorn, and will be accessible at http://127.0.0.1:8000.
Testing the API
Once the server is up and running, users can access the FastAPI documentation interface at http://127.0.0.1:8000/docs. The interactive documentation allows users to test the API by providing input texts in JSON format. For example:
{
"texts": [
"My phone dies by noon even if I don't use it.",
"I dropped it on the sidewalk and the glass shattered.",
"This is the best device I have ever purchased!"
]
}
Upon executing this request, the pipeline will return predictions corresponding to the input texts.
Conclusion
This article outlines the steps to construct a reliable and efficient text classification service using Scikit-LLM and FastAPI. The approach avoids the limitations of cloud APIs by utilizing a self-hosted solution, enabling better control over model performance and operational costs.
Source: machinelearningmastery.com


