Prompts, context and structured output
Why it matters
- In production, LLM responses are untrusted input. A malformed JSON response can crash your app if you parse it without validation. You must validate it with
kotlinx.serializationin Kotlin before passing it to the UI. - Context window is finite. Sending full conversation history or large documents silently truncates or degrades quality. You must chunk and prioritise context.
- API keys in
BuildConfigorlocal.propertiesare extractable from a decompiled APK. They must live on your server, never in the app module. - Senior interviews ask: 'How do you guarantee structured output?' and 'How do you handle hallucination in the UI?' The honest answers show seniority.
The simple explanation
- A prompt is a brief for a new intern: role, context, task, and output format.
- The context window is the intern's short-term memory. Too much and they forget the beginning.
- Structured output is asking for a filled-in form instead of a free-form paragraph.
- Hallucination is the intern confidently stating a fact they made up. It is not a bug; it is how token prediction works.
- Temperature is how creative versus literal the intern is. Low for forms, high for brainstorming.
A prompt is a single string sent to an LLM. It has three parts: a system instruction (role and rules), context (retrieved data, conversation history, user profile), and the user query. The model reads all of it as one flat sequence of tokens and predicts the next token, one at a time, until it hits a stop token.
Context window is the maximum number of tokens the model can process in one call. It is not infinite. If your prompt plus context exceeds it, the API either rejects the request with an error or (in some chat setups) older content is dropped. In Android, this means you must chunk long documents, summarise old conversation turns, and prioritise the most relevant context. Check the current docs for the window size of your chosen model.
Structured output means you embed a JSON schema in the prompt: "Respond ONLY with a JSON object: {"name": string, "confidence": number}". But the model can still return malformed JSON, extra prose, or a wrong shape. You must validate the response in Kotlin using kotlinx.serialization (Json.decodeFromString<T>). Treat the LLM response like untrusted network input. Some APIs can enforce a response schema for you (Gemini through Firebase AI Logic, and the ML Kit Prompt API's structured output support), which makes valid JSON far more likely, but you still validate.
Hallucination is not a bug. The model predicts plausible tokens; it does not check facts. Design your UI to show confidence, cite sources, and let the user verify. Never trust a single response for critical data.
| Part | What it is | Common mistake |
|---|---|---|
| System instruction | Role, rules, output format | Too vague; no schema |
| Context | Retrieved docs, history | Exceeds context window |
| User query | The actual question | Buried in noise |
| Temperature | Low = focused, high = varied | Left at default for structured tasks |
| Tokens | Roughly 4 chars per English token | Miscounting context size |
API keys must stay on your server. Never ship them in the APK. For on-device models, check the current docs for supported devices and model sizes.
Notes
- A prompt is one string: system instruction + context + user query. The model sees it as a flat token sequence, not as separate fields.
- Context window is the hard limit on tokens per call. Exceeding it causes an error or dropped context. Check the current docs for the limit of your chosen model.
- Structured output: embed a JSON schema in the prompt, but always validate the response with
kotlinx.serializationin Kotlin. Models can return invalid JSON or extra prose. - Hallucination is normal model behaviour. The model predicts the next token; it does not verify facts. Design UI with confidence indicators and source citations.
- Temperature controls randomness. For structured output and factual tasks, use a low value. For creative tasks, a higher value is fine. The exact range depends on the model.
- API keys must live on your server. Never put them in
BuildConfig,local.properties, or any file in the app module. An APK can be decompiled in minutes. - Latency and cost scale with token count. A long response costs and takes longer than a short one. Set a max output token limit and stream responses for perceived speed.
Json { ignoreUnknownKeys = true }handles extra fields the model adds. Missing required fields and wrong types still throw, and you must still check values (ranges, allowed strings) yourself.- If your API supports a response schema (structured output mode), use it. It reduces bad JSON but does not remove the need to validate.
- For on-device models, check the current docs for supported devices and model sizes. App size, battery drain, and thermal limits are real constraints.
- In interviews, 'how do you guarantee structured output?' is a trap question. The honest answer is: you cannot guarantee it; you validate, retry, and show a fallback UI.
Code example
This shows the two functions every Android AI feature needs: one that builds a prompt with context and a JSON schema, and one that validates the raw model response with kotlinx.serialization before your UI touches it.
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
@Serializable
data class ProductSuggestion(
val name: String,
val reason: String,
val confidence: Double
)
// Build the prompt: system role + context + query + schema
fun buildPrompt(userQuery: String, context: List<String>): String {
val contextBlock = context.joinToString("\n") { "- " + it }
return "You are a product assistant. " +
"Context:\n$contextBlock\n\n" +
"User question: $userQuery\n\n" +
"Respond ONLY with JSON: " +
"{\"name\": string, \"reason\": string, \"confidence\": number}"
}
// Create once and reuse
private val json = Json { ignoreUnknownKeys = true }
// Validate the raw model output before the UI sees it
fun parseSuggestion(raw: String): Result<ProductSuggestion> {
return runCatching {
json.decodeFromString<ProductSuggestion>(raw)
}.onFailure {
// Model returned invalid JSON or wrong shape.
// Log the raw string, retry once with a stricter prompt,
// then show a fallback UI to the user.
}
}@Serializable+Json.decodeFromStringis the standardkotlinx.serializationpath.ignoreUnknownKeys = trueabsorbs extra fields the model adds, but missing required fields still throw.runCatchingwraps parsing so a malformed response becomes aResult.failureinstead of a crash. TheonFailureblock is where you log, retry, or fall back.- The schema is embedded as a plain string in the prompt. For complex schemas, keep the schema string next to the
@Serializableclass and cover both with a test so they do not drift.
Run the idea in plain Kotlin
fun main() {
val contextItems = listOf(
"User prefers dark mode",
"User is in Berlin, Germany",
"User last searched for hiking boots"
)
val userQuery = "Recommend an activity for this weekend"
// Build prompt with context
val contextBlock = contextItems.joinToString("\n") { "- " + it }
val prompt = "Context:\n" + contextBlock + "\n\nQuestion: " + userQuery
// Simulate a context window limit (in characters for this simulation)
val maxChars = 150
val promptLength = prompt.length
println("Prompt length: " + promptLength + " chars")
println("Max window: " + maxChars + " chars")
if (promptLength > maxChars) {
println("WARNING: exceeds context window by " + (promptLength - maxChars) + " chars")
println("Truncated: " + prompt.substring(0, maxChars))
} else {
println("Prompt fits in context window")
}
// Simulate structured output validation
val validResponse = "{\"activity\": \"hike\", \"confidence\": 0.8}"
val invalidResponse = "I think you should go hiking! Maybe a museum too."
val validCheck = validResponse.startsWith("{") && validResponse.contains("\"activity\"")
val invalidCheck = invalidResponse.startsWith("{") && invalidResponse.contains("\"activity\"")
println("")
println("Valid JSON check passed: " + validCheck)
println("Invalid response check passed: " + invalidCheck)
if (invalidCheck) {
println("Action: parse and use the response")
} else {
println("Action: reject and show fallback UI")
}
}In production
- A developer placed the LLM API key in
BuildConfigfor local testing and forgot to remove it before the release build. - The key was extracted from the APK on a public decompiler site. Billing spiked significantly in a single day.
- The dashboard showed a massive increase in token usage with no corresponding user growth.
- The team moved the key to a server-side proxy. The Android app now calls the company backend, which calls the LLM.
- A CI step was added that greps the built APK for known key patterns and fails the build if one is found.
- All existing keys were rotated and the old key was revoked.
- The app asked the model for JSON but called
Json.decodeFromStringdirectly on the main thread without arunCatchingwrapper. - On certain inputs the model returned prose instead of JSON. The decode threw, and the crash hit the UI thread.
- Crash analytics showed a spike in sessions ending with a
SerializationExceptionstack trace.
- Parsing was wrapped in
runCatchingwith a retry using a stricter prompt that repeated the schema. - A fallback UI ("I could not answer that, try rephrasing") was shown when both attempts failed.
- A test suite of known-bad model responses was added to CI to catch regressions.
Common mistakes
- Putting the API key in BuildConfig or local.properties. The key is baked into the APK and extractable in minutes. It must live on your server; the app calls your backend, not the LLM directly.
- Trusting the model's JSON without validation. Models return malformed JSON, extra prose, or wrong types. Always parse with
kotlinx.serializationinsiderunCatchingand show a fallback UI on failure. - Sending the full conversation history every turn. The context window is finite. Old turns get truncated or the request is rejected. Summarise or drop old turns and keep only the most relevant context.
- Treating hallucination as a bug to fix in the model. Hallucination is inherent to next-token prediction. You cannot eliminate it. Design the UI to show confidence, cite sources, and let the user verify.
- Leaving temperature at the default for structured tasks. A high temperature adds randomness that makes broken JSON more likely. Set a low value when you need consistent, schema-conforming output.
- Not setting a max output token limit. Without a cap, the model can generate thousands of tokens, increasing latency and cost. Set a reasonable upper bound for your use case.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How do you ensure an LLM returns valid JSON in a production Android app?”
“What happens when a prompt exceeds the context window? How do you handle it?”
“A user reports that the AI feature gives wrong answers. How do you investigate?”
“Where should the LLM API key live in an Android app architecture?”
Quiz
What is the context window of an LLM?
What should you do with a JSON response from an LLM in a Kotlin app?
Where should an LLM API key be stored in an Android project?
What is hallucination in the context of LLMs?
0 of 4 answered
Mini task
15-minute exercise: Build and validate a structured prompt
-
Create a data class. In a new Kotlin file, define a
@Serializabledata classWeatherSummarywith fieldscity: String,tempCelsius: Int, andadvice: String. Add thekotlinx-serialization-jsondependency to yourbuild.gradle.ktsif it is not already there. -
Write
buildWeatherPrompt. Create a functionfun buildWeatherPrompt(city: String, history: List<String>): Stringthat concatenates a system instruction ("You are a weather assistant"), the history items joined with newlines, the city name, and a JSON schema string:{"city": string, "tempCelsius": number, "advice": string}. Use string concatenation with+. -
Write
parseWeather. Create a functionfun parseWeather(raw: String): Result<WeatherSummary>that usesJson { ignoreUnknownKeys = true }andrunCatching { json.decodeFromString<WeatherSummary>(raw) }. In theonFailureblock, print the raw string withprintln(useLog.wwhen this runs inside the app). -
Test with two inputs. In a
mainfunction or a test, callparseWeatherwith a valid JSON string and with the plain text "It is sunny and warm.". Print theResultfor each. Confirm the first isSuccessand the second isFailure. -
Add a context-window check. Before building the prompt, compute
history.joinToString("\n").lengthand print a warning if it exceeds 2000 characters. This simulates a token-budget check.
Done when: both test inputs produce the expected Result type, the warning prints for a long history, and the code compiles with no warnings.