VillageSQL is a drop-in replacement for MySQL with extensions.
All examples in this guide work on VillageSQL. Install Now →
ai_prompt() lets you do the classification directly in SQL, keeping the logic close to the data and eliminating the export/import cycle.
The Problem: Classification Outside SQL
The typical workflow without VillageSQL:With VillageSQL: ai_prompt() as a Classifier
Validating classification output
Models occasionally return unexpected output. Store results as-is and validate separately:Multi-label classification
When a row can belong to more than one category, ask for a JSON array and store it in aJSON column:
Building a confidence score
Ask the model to return structured JSON with both a label and a confidence level:Prompt Patterns That Work
| Goal | Prompt pattern |
|---|---|
| Single label | ”Classify as X, Y, or Z. Reply with one word only.” |
| Confidence scoring | {"label": "X", "confidence": "high/medium/low"} |
| Multi-label | ”Return a JSON array of applicable labels from [X, Y, Z].” |
| Binary decision | ”Does this text contain X? Reply yes or no.” |
Frequently Asked Questions
How accurate is AI classification compared to a trained model?
A capable model like Claude Haiku achieves high accuracy on straightforward classification tasks without any training data. For domain-specific categories with subtle distinctions, you may need to provide examples in the prompt or use a larger model.Can I classify rows as they’re inserted using a trigger?
Yes, but use caution — a trigger that callsai_prompt() on every INSERT makes every write take 5–30 seconds. Better to classify in a periodic batch job and accept a short delay before labels are available.
How do I handle rows where the model returns NULL?
ai_prompt() returns NULL when the API call fails. In your batch loop, keep running UPDATE until no NULLs remain, with retry logic for transient failures.
What model should I use for classification?
Start withclaude-haiku-4-5-20251001 or gpt-4o-mini — both are fast and cheap. Step up to a more capable model only if accuracy is unacceptable.
Troubleshooting
| Problem | Solution |
|---|---|
FUNCTION ai_prompt does not exist | Run INSTALL EXTENSION vsql_ai |
| Returns NULL | Check API key and max_execution_time; verify model name |
| Labels outside the allowed set | Add a post-UPDATE query to normalize unexpected values |
| JSON parse errors on structured output | Add “Return only valid JSON, no other text” to the prompt |
| Low accuracy | Add 2–3 examples to the prompt; try a more capable model |

