LLM features need boring engineering: lessons from my projects

Practical lessons from BuySmart AI, DataTalk Pro and TIPS on caching model output, building fallbacks, placing safety checks and fitting models to real hardware.

Adding a language model to a product takes an afternoon. Making that feature predictable, affordable and safe takes much longer, and almost none of that work involves the model. These lessons come from three projects with different shapes: BuySmart AI, DataTalk Pro and TIPS.

Cache the output, not just the input

BuySmart originally cached raw product data but re-ran the AI analysis every time someone searched for the same product. The fix is documented in the repository, and its problem statement is worth reading closely:

  • Re-running the AI analysis each time, which was expensive and slow.
  • Returning potentially different results for the same product.
  • Wasting API calls to the AI service.

The second point is the one people miss. Models are not deterministic, so uncached analysis means the same product can get a different score on each search. For a tool whose purpose is an objective recommendation, that damages trust more than slowness does. The fix checks for a stored result first:

AnalysisServiceImpl.java
@Override
public Optional<AnalysisResult> getLatestAnalysisForProduct(String productId) {
    return analysisRepo.findTopByProduct_ProductIdOrderByAnalyzedAtDesc(productId);
}

Responses from this path carry a cached: true flag, so the frontend knows what it is showing. Caching also creates the next problem: the README lists stale prices as a known issue, because the raw product cache has no strict expiry. That is a fair trade to make as long as it is written down.

Decide what happens when the model is unavailable

Hosted models go down and rate limits get hit. BuySmart handles this with an explicit switch: when the Python service is unavailable, the ai.enabled property routes requests to basic local parsing with Jsoup. The result is less insightful, and the user still gets an answer.

Designing this forces a useful question: what is the least useful version of this feature that is still honest? A plain comparison of specifications is fine. Inventing a score to fill the gap is not.

Ask for structure, then validate it

If application code consumes model output, free-form text is a liability. BuySmart's AI service returns structured JSON with a recommendation, score, pros and cons, shaped through Pydantic. This gives the UI something dependable to render.

Structure does not make the content true. The README says so directly: Gemini can misinterpret generic descriptions when the source data is sparse. A schema guarantees the shape of an answer and nothing about whether it is correct.

A prompt is not a security boundary

This is the lesson I most want to pass on, because the mistake was in my own code, and it went unnoticed until I reread that code for this article. DataTalk Pro lets people query a MySQL database in plain English. The prompt that wrote the final answer contained this rule:

If the SQL query contains any dangerous operations like DELETE, DROP, UPDATE, or ALTER, do not execute the query. Instead, respond with "I'm sorry, but I cannot execute queries that modify or delete data."
DataTalk Pro, src/app.py, before the fix

It reads like a guard. Now look at the order of the chain that used it:

src/app.py before the fix, with comments added
chain = (
    RunnablePassthrough.assign(query=sql_chain).assign(
        schema=lambda _: db.get_table_info(),
        response=lambda vars: db.run(vars['query'])  # runs here
    )
    | prompt   # the "do not execute" rule is read here
    | llm
    | StrOutputParser()
)

db.run happened before the prompt was ever formatted. If the first model generated a DELETE, the statement had already reached the database by the time the second model was told not to run it. The user could get a polite refusal for something that had already happened. Nothing looked wrong in a quick demo, because the model rarely writes destructive SQL when asked ordinary questions.

To confirm it, I ran the real function against a throwaway database, with a fake model returning the query. A generated DELETE emptied the table and a DROP removed it.

The principle is simple: an instruction to a model is a request, not an enforcement. Real controls belong in code and in permissions, in that order of convenience and the reverse order of strength.

The fix moves the decision out of the prompt and ahead of the database call. Generated SQL is checked first, and a refused query returns without ever being run.

src/app.py
query = sql_chain.invoke({
    "chat_history": chat_history,
    "question": user_query
})
try:
    safe_query = check_read_only(query)
except UnsafeQueryError:
    return REFUSAL

The check itself is an allowlist. A query runs only if it parses as a single known read statement, and anything else is refused, including SQL that can't be parsed.

src/sql_guard.py, shortened
statements = [s for s in sqlglot.parse(cleaned, read="mysql") if s is not None]
if len(statements) != 1:
    raise UnsafeQueryError("Only one statement can run at a time.")

statement = statements[0]
if not isinstance(statement, _READ_STATEMENTS):
    raise UnsafeQueryError(f"{type(statement).__name__} statements are not allowed.")

for node in statement.walk():
    if isinstance(node, _FORBIDDEN_PARTS):
        raise UnsafeQueryError(f"{type(node).__name__} is not allowed.")

Parsing is better than searching for the word DELETE, because text matching fails in both directions: it misses REPLACE and it wrongly blocks a column called deleted_at. Walking the whole statement matters because a SELECT can still do more than read, for example by taking locks with FOR UPDATE. With the fix in place, the same test leaves every row where it was.

The strongest control still sits outside the application: connect with a database user that only has SELECT rights. Then even a bug in the check cannot change any data.

Fit the model to the machine you have

TIPS analyses recorded interviews and runs its model locally. Its semantic stage uses Qwen2.5-3B-Instruct with 4-bit NF4 quantisation, which lets it run on GPUs with around 3 GB of VRAM. That constraint shaped the system more than any accuracy benchmark would.

It also helps that the LLM is one stage out of six. Timing, speech, gaze and pitch are extracted with conventional tools such as faster-whisper, librosa, OpenCV and MediaPipe. The model only handles what needs language understanding: scoring each answer against the job description.

  1. Timebase
  2. Extraction
  3. Segmentation
  4. Behaviour
  5. Semantic scoring
  6. Aggregation
TIPS analysis stages

This is a pattern worth copying. Use deterministic code wherever it can do the job, and spend the model on the part that truly needs it. The result is cheaper, easier to test, and easier to explain when someone asks why a score came out the way it did.

A short checklist

  • Should two identical requests get the same answer? If so, cache the output.
  • What does the user see when the model is unavailable?
  • Is the output validated against a schema before code touches it?
  • Does any action happen before a check that claims to prevent it? Read the actual execution order.
  • Which permissions would limit the damage if every check failed?
  • Which parts of this pipeline could be ordinary code?

None of this is glamorous, and that is the point. The model gets the attention, while this surrounding work decides whether people can rely on the feature.