AI Prompt Classification and Routing Project

Artificial Intelligence project 11

AI Prompt Classification and Routing Project

Build a complete prompt classification and routing workflow with reproducible Python code, transparent inputs, reviewable output, and responsible-use limits.

Explore AI training in VizagView all project ideas

AI objective

Select a specialised handler for known prompt types while withholding low-confidence routing.

Data or knowledge source

Twenty synthetic prompts labelled summarisation, translation, code help, or data analysis.

Requirements

  • Python 3.10 or later
  • A terminal or command prompt
  • python -m pip install scikit-learn
  • About 45-60 minutes to build and review

How the system works

Train a TF-IDF logistic-regression classifier, read class probabilities, and return no route when confidence is below the review threshold.

Validation checklist

  • Routing does not execute a downstream action
  • Low confidence remains visible
  • Labels are balanced in the teaching data
  • Unsupported goals are treated as a known gap

Complete Python code

Save the program as ai_prompt_classification_router.py. The code runs locally and requires no paid API key or model download.

"""Route prompts to specialised handlers with a review threshold."""

from __future__ import annotations

from dataclasses import dataclass
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline


PROMPTS = {
    "summarize": ["summarize this article", "make a short summary", "give me the key points", "condense this report", "shorten the following text"],
    "translate": ["translate this to Hindi", "convert into French", "provide a Spanish translation", "translate the paragraph", "change this into English"],
    "code_help": ["debug this Python function", "explain this SQL error", "write a unit test", "fix my code", "review this program"],
    "data_analysis": ["calculate monthly revenue", "analyse customer churn", "show the sales trend", "compare conversion rates", "build a KPI table"],
}


@dataclass(frozen=True)
class Decision:
    route: str | None
    confidence: float
    needs_review: bool


def train_prompt_router() -> Pipeline:
    texts, labels = [], []
    for label, examples in PROMPTS.items():
        texts.extend(examples)
        labels.extend([label] * len(examples))
    return Pipeline([("tfidf", TfidfVectorizer(ngram_range=(1, 2))),
                     ("classifier", LogisticRegression(max_iter=1000, random_state=42))]).fit(texts, labels)


def route_prompt(model: Pipeline, prompt: str, threshold: float = 0.42) -> Decision:
    probabilities = model.predict_proba([prompt])[0]
    index = int(probabilities.argmax())
    confidence = float(probabilities[index])
    return Decision(str(model.classes_[index]) if confidence >= threshold else None, confidence, confidence < threshold)


def main() -> None:
    model = train_prompt_router()
    for prompt in ("Please summarize this report", "Why is my Python test failing?", "Book a table for dinner"):
        print(prompt, "->", route_prompt(model, prompt))


if __name__ == "__main__":
    main()

Run the project

  1. Create and activate a virtual environment.
  2. Install dependencies with python -m pip install scikit-learn when packages are required.
  3. Run python ai_prompt_classification_router.py.
  4. Review confidence, fallbacks, sources, or error metrics rather than accepting output automatically.
  5. Test additional normal, edge, unsupported, and adversarial inputs.

Expected output

Selected route or null, confidence, and needs-review status.

Accuracy, privacy, and responsible-use limits

Prompt wording is open-ended and adversarial. Validate inputs, permissions, downstream tool arguments, and user confirmation before any routed action changes external state.

Ways to extend the project

Add an unknown route, prompt-injection tests, multilabel handling, calibrated thresholds, permission policies, and tool-level audit logs.

Continue learning Artificial Intelligence

Try the next project, return to the Softenant project library, or explore the AI training in Vizag for guided NLP, retrieval, evaluation, automation, and responsible AI practice.