Prompting is a bad DSL | Treat the model like a third-party API with no types
7 min readweb-dev
A language model behind your backend is a remote dependency with no types, no determinism and variable latency. The patterns for handling that are the ones you already use for unreliable third-party APIs: schemas at the boundary, queues, idempotency, retries and a fallback path.
Most writing about prompts treats them as a craft: phrasing, examples, magic words. From the backend side the picture is simpler. A model call is a request to a remote service that has no types, no compiler, no fixed latency and a non-trivial rate of answers that are wrong. I have integrated services like that before, and the patterns carry over almost unchanged.
This post walks through them with one example feature: classifying incoming support tickets into a category, a priority and a one-line summary. I use NestJS, a queue and zod, because that is the stack the rest of this blog is about.
What a prompt does not give you
A compiler gives you guarantees before the code runs. A function declared to return { category: 'billing' | 'bug' | 'access' | 'other' } cannot return anything else. A prompt that says “respond with JSON containing a category” is the same declaration enforced by hope.
That is why I think of prompt engineering, in the part that is about output format, as a compensation layer for missing types. “Return only valid JSON”, “do not add commentary”, the example block at the bottom: all of it is a type signature written in prose to something that may or may not honour it. It is a domain-specific language, and a bad one, because it has no parser and no error messages. It is also what we have, so the useful question is what to build around it.
Validate at the boundary
The first rule is the one from the custom validator post: nothing crosses the boundary into your domain without being checked. The model’s output is untrusted input.
Providers now offer schema-constrained output, and you should use it where it exists. It still does not remove the check. OpenAI’s documentation says only Structured Outputs ensure schema adherence, and that a refusal does not necessarily follow your schema, so you check for a refusal before parsing. A response cut off at the token limit is incomplete JSON. Anthropic’s structured outputs use constrained decoding, and their documentation notes that constraints such as minimum, maximum and minLength are not enforced by the API schema; the SDK helpers move them into field descriptions and validate the response client-side. The decoder guarantees shape, and your own rules still need your own code.
So the service parses and validates every response, and it has exactly one failure type:
import { Injectable } from '@nestjs/common';
import { z } from 'zod';
export const Triage = z.object({
category: z.enum(['billing', 'bug', 'access', 'other']),
priority: z.number().int().min(1).max(4),
summary: z.string().min(1).max(280),
});
export type Triage = z.infer<typeof Triage>;
export class ModelOutputError extends Error {}
export interface ModelClient {
complete(input: { prompt: string; timeoutMs: number }): Promise<string>;
}
@Injectable()
export class TriageService {
constructor(private readonly model: ModelClient) {}
async triage(ticketText: string): Promise<Triage> {
const raw = await this.model.complete({
prompt: buildPrompt(ticketText),
timeoutMs: 20_000,
});
let json: unknown;
try {
json = JSON.parse(raw);
} catch {
throw new ModelOutputError('response is not JSON');
}
const parsed = Triage.safeParse(json);
if (!parsed.success) {
throw new ModelOutputError(parsed.error.message);
}
return parsed.data;
}
}
ModelClient is an interface on purpose. The provider is a seam, and a fake that returns canned strings makes every failure path testable without a network call. The timeout is part of the contract, not an afterthought.
Structural validation is the floor. If the model returns an identifier, such as an assignee or a related ticket, the check from the relationship-validator post applies as is: does that record exist? A well-formed ID that points at nothing is the most common kind of plausible nonsense.
Non-determinism is an operational property
With a typed function you write an assertion once and it holds. With a model call the same input can produce different outputs. Setting the temperature to 0 does not fix this in practice: Thinking Machines showed that LLM inference endpoints are still not deterministic even at temperature 0, and traced it to how batching and kernels are arranged on the server, which you do not control.
The consequence is for testing. You cannot assert on one output, so you keep a fixed set of tickets with known good answers and measure how often the pipeline gets them right. That is a regression suite with a pass rate in place of a pass/fail, and it is what gates a prompt change or a model upgrade. A model version change alters behaviour without a line of your code changing, which makes pinning the model version in config worth the extra line.
Latency and cost belong in the design
A third-party API with variable latency does not get called inside a user’s HTTP request when it can be avoided. The reasoning in the queues post applies directly: accept the ticket, enqueue the work, answer the user, let a worker deal with the slow dependency. The same arrangement gives you rate control and a place to put retries.
@Injectable()
export class TicketsService {
constructor(@InjectQueue('triage') private readonly queue: Queue) {}
enqueueTriage(ticketId: string) {
return this.queue.add(
'triage',
{ ticketId },
{
jobId: `triage-${ticketId}`,
attempts: 3,
backoff: { type: 'exponential', delay: 1000 },
},
);
}
}
The attempts and backoff options are BullMQ’s retry mechanism: without attempts a failed job is not retried, and without backoff it is retried immediately. The custom jobId makes enqueueing the same ticket twice a no-op, which matters for the next section. BullMQ does not allow : in a custom id, hence the hyphen.
Retries when the retry may differ
Retrying a failed HTTP call to a payment provider is safe if the call is idempotent. A retried model call is different in one way: it may legitimately return a different answer. That makes it more important, not less, to decide which result wins and to make sure a late duplicate cannot overwrite it.
The processor below handles it. It exits early if the ticket already has a triage, so a redelivered or duplicate job changes nothing, and it records where the result came from.
The degraded path
The question most integrations skip is what the feature does when the model is down, slow, or wrong three times in a row. In the processor, the last attempt does not throw. It writes a fallback value and marks it as such:
@Processor('triage')
export class TriageProcessor extends WorkerHost {
constructor(
private readonly tickets: TicketsRepo,
private readonly triage: TriageService,
) {
super();
}
async process(job: Job<{ ticketId: string }>): Promise<void> {
const ticket = await this.tickets.findById(job.data.ticketId);
if (ticket.triage) return;
try {
const result = await this.triage.triage(ticket.body);
await this.tickets.saveTriage(ticket.id, result, { source: 'model' });
} catch (err) {
const lastAttempt = job.attemptsMade + 1 >= (job.opts.attempts ?? 1);
if (!lastAttempt) throw err;
await this.tickets.saveTriage(ticket.id, FALLBACK, { source: 'fallback' });
}
}
}
For triage the fallback is category: 'other' with a middle priority, which routes the ticket to a human queue. The source field is the part I care about. Months later, someone asking why a ticket was routed oddly can see whether a model decided it or the fallback did, and a dashboard can show the fallback rate, which is the cheapest health metric this feature has.
Where the analogy stops
A third-party API publishes a contract you can read. A model’s contract is statistical. Everything above makes failures visible and bounded, but none of it catches an answer that is well-formed, passes validation and is wrong. A ticket classified as a low-priority billing question when it is an outage looks identical to a correct one. The measurable defence is the fixed evaluation set and a sample of real outputs reviewed by a person. For anything where a wrong answer costs money or trust, the model proposes and a person decides.
The schema, the queue, the retry policy and the fallback make up most of the engineering. The prompt is a small part of the work, and the reason it gets the attention is that it is the only part that looks new.