Chat state, history and context limits
Why it matters
- Every
sendMessageon a chat sends the full conversation so far. Unbounded history hits the context window, the request is rejected, and the user sees a blank screen or an error. - Interviewers ask how you keep a long conversation inside a fixed token budget. The answer is trimming, summarisation, or a sliding window, and you must explain the trade-off between recall and cost.
- Model output is untrusted text. A prompt-injection payload can look like a valid command. If your app treats a
Contentstring as a navigation intent or a Room write, you have a security bug. - Process death is normal on Android. A ViewModel survives rotation, but not process death. If history lives only in a
StateFlow, the user loses the conversation when the system kills the app in the background. Room persistence is the fix.
The simple explanation
- A chat window is like a phone call transcript you re-read before every reply.
- The context window is the length of paper you can fit on the desk.
- Trimming is folding old pages into a summary note.
- Summarising is writing 'they discussed X' instead of pasting 50 pages.
- Persisting to Room is saving the transcript in a drawer so you can resume after a break.
- Validating output is not acting on a note that says 'delete the file' without checking who wrote it.
The model is stateless. Each request must carry the conversation it should see. Firebase AI Logic's startChat(history) wraps a List<Content> in a Chat object that appends new turns in memory, and every sendMessage ships all prior turns to the server.
The context window is a hard token limit set by the model. Exceed it and the API rejects the request. You cannot know the exact limit from code; check the current docs for supported models and their windows.
In a ViewModel you own the history list, not the Chat object. This lets you trim, persist, and replay. The common pattern:
| Concern | Where it lives | Why |
|---|---|---|
| In-memory turns | StateFlow<List<ChatTurn>> in ViewModel | UI reads it; Compose collects it |
| Durable turns | Room table chat_turns | Survives process death |
| Trim / summarise | ViewModel before each call | Keeps payload under the window |
| Model call | generativeModel(name, systemInstruction = ...).startChat(trimmed) | Sends only what fits |
| Output validation | A parser or allow-list before acting | Prevents injection |
Trimming strategies: sliding window (drop oldest N turns), token budget (count approximate tokens, drop from the front until under budget), or summarise (call the model once to compress old turns into one short summary turn). Sliding window is cheapest; summarising costs an extra call but preserves more meaning.
Never treat model text as a command. Parse it through a strict schema (JSON with a responseSchema in Firebase AI Logic, or a sealed class on your backend) and reject anything that does not match.
Notes
- The model has no memory between calls. The
Chatsends its fullList<Content>every time.startChat(history)just wraps that list in memory; it does not store state server-side. - The context window is a token limit, not a character or turn limit. Approximate tokens as
chars / 4for a rough budget, or call the SDK'scountTokensfor an exact count. Check the current docs for the exact window per model. - Keep the authoritative history in a
StateFlow<List<ChatTurn>>in the ViewModel and mirror it to Room. After process death, reload from Room and callstartChat(savedHistory). - Trim before every call. A sliding window of the last N turns is the simplest strategy. A token-budget trimmer counts approximate tokens and drops from the front. Summarising old turns into one short summary preserves meaning at the cost of an extra API call.
- Never execute model output as a command. Parse it through a strict schema (JSON
responseSchema, a sealed class, or an allow-list of actions). A prompt-injection payload can mimic a valid instruction. - Cancellation: collect the
Flow<GenerateContentResponse>fromsendMessageStreaminsideviewModelScope. When the user leaves, the scope cancels and the stream stops. Do not cancel the Room write that persists the partial turn. - Do not put an API key in
BuildConfigor in app code. Firebase AI Logic uses a key-less proxy behind Firebase App Check. For Claude, OpenAI, or any other provider, the key lives on your backend; the app calls your backend. - Put the system prompt in
systemInstructionon the model, not in the history, so trimming never drops it. Gemini history turns use the rolesuserandmodel. Keep the most recent turns intact. - A
Chatobject fromstartChatmaintains its own internal history. If you also keep a ViewModel list, you can get two sources of truth. Prefer the ViewModel list and pass a freshstartChat(trimmed)each time, or sync explicitly. - Room schema for turns:
id,role(user/model),text,timestamp,conversationId. Index onconversationId + timestampfor fast ordered reads.
Code example
This ViewModel trims a chat history to a token budget before each call to Firebase AI Logic, persists turns to Room, and validates model output through a sealed result type instead of acting on raw text.
// The model is created once with the system prompt as systemInstruction:
// Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
// modelName = nameFromConfig,
// systemInstruction = content { text("You are a concise assistant.") })
class ChatViewModel(
private val ai: GenerativeModel,
private val repo: ChatRepository, // Room-backed
) : ViewModel() {
private val _turns = MutableStateFlow<List<ChatTurn>>(emptyList())
val turns: StateFlow<List<ChatTurn>> = _turns.asStateFlow()
// Rough budget; read the real limit for your model from config or docs.
private val maxTokens = 8_000
fun send(userText: String) = viewModelScope.launch {
// Trim the history BEFORE adding the new turn, so it is not sent twice.
val trimmed = trimHistory(_turns.value, maxTokens)
val userTurn = ChatTurn(Role.USER, userText)
_turns.update { it + userTurn }
repo.insert(userTurn)
// Build a fresh Chat each call so the ViewModel owns history.
val chat = ai.startChat(history = trimmed.map { it.toContent() })
try {
val response = chat.sendMessage(userText)
val modelTurn = ChatTurn(Role.MODEL, response.text.orEmpty())
_turns.update { it + modelTurn }
repo.insert(modelTurn)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
_turns.update { it + ChatTurn(Role.MODEL, "[failed, tap to retry]") }
}
}
// ChatTurn.toContent() maps to content(role = "user" or "model") { text(...) }.
private fun trimHistory(turns: List<ChatTurn>, budget: Int): List<ChatTurn> {
var used = 0
val kept = mutableListOf<ChatTurn>()
for (turn in turns.reversed()) {
val cost = turn.text.length / 4 + 4 // rough token estimate
if (used + cost > budget) break
used += cost
kept.add(0, turn)
}
return kept
}
}trimHistorywalks from the newest turn backward and stops when the running token estimate exceeds the budget. The system prompt is set once assystemInstructionon the model, so trimming can never drop it.- History is trimmed before the new user turn is added, because
sendMessage(userText)sends that turn itself. - A fresh
startChat(trimmed)is created per call. This avoids theChatobject's internal history drifting from the ViewModel'sStateFlow, which is the source of truth for Room and UI. - The reply is shown as plain text. If a reply can trigger an action, parse it into a sealed type with an allow-list first; never act on raw text.
viewModelScope.launchties the coroutine to the ViewModel lifecycle. If the user leaves, the scope cancels the call, but the Room insert for the user turn already completed.
Run the idea in plain Kotlin
data class Turn(val role: String, val text: String)
fun estimateTokens(text: String): Int {
return text.length / 4 + 4
}
fun trimHistory(turns: List<Turn>, budget: Int): List<Turn> {
var used = 0
val kept = mutableListOf<Turn>()
val reversed = turns.reversed()
for (turn in reversed) {
val cost = estimateTokens(turn.text)
if (used + cost > budget) break
used += cost
kept.add(0, turn)
}
return kept
}
fun main() {
val turns = listOf(
Turn("user", "Hi, I am learning Android."),
Turn("user", "Hello, can you help me with Kotlin coroutines?"),
Turn("model", "Sure, coroutines are a concurrency mechanism in Kotlin that lets you write asynchronous code in a sequential style."),
Turn("user", "What about structured concurrency?"),
Turn("model", "Structured concurrency means child coroutines are scoped to a parent. When the parent completes, all children are cancelled."),
Turn("user", "And how does viewModelScope relate to that?"),
Turn("model", "viewModelScope is a CoroutineScope tied to the ViewModel lifecycle. It cancels all children when the ViewModel is cleared."),
Turn("user", "Can you show a cancellation example?"),
Turn("model", "Yes. launch in viewModelScope, and when the user leaves the screen the scope cancels the coroutine automatically.")
)
val budget = 120
val trimmed = trimHistory(turns, budget)
println("Original turns: " + turns.size)
println("Trimmed turns: " + trimmed.size)
println("---")
for (i in trimmed.indices) {
val t = trimmed[i]
println("[" + i + "] " + t.role + ": " + t.text.take(60) + "...")
}
println("---")
var total = 0
for (t in trimmed) {
total += estimateTokens(t.text)
}
println("Estimated tokens in trimmed set: " + total + " / " + budget)
}In production
- Users reported that after roughly 30-40 messages the chat screen went blank and showed a generic error toast.
- Server logs showed 400 responses with a 'context length exceeded' message from the model provider.
- The ViewModel appended every turn to a
MutableStateFlowand passed the full list tostartChatwithout trimming.
- Added a
trimHistorystep that keeps the most recent turns under a token budget, estimated viatext.length / 4, with the system prompt moved tosystemInstruction. - Persisted turns to Room so the user could scroll back to older messages even after trimming the in-memory list.
- Added a unit test that feeds 100 turns and asserts the trimmed list stays under the token budget.
- A user pasted a web page into the chat. The page contained text that looked like a JSON command:
{"action": "delete_all_notes"}. - The ViewModel parsed the model's response as a command and called a Room delete. All saved notes were gone.
- The model echoed the injected text back, and the app treated it as a valid instruction.
- Replaced the raw-text handler with a sealed
ChatResulttype. OnlyChatResult.Okwith a validated action enum triggers a side-effect. - Added a server-side allow-list: the backend rejects any action string not in a fixed set.
- Added a confirmation dialog for destructive actions, so a single model response cannot delete data without user consent.
Common mistakes
- Unbounded history in the ViewModel. Every turn is appended and never removed. After enough turns the payload exceeds the context window and the request fails. Trim or summarise before each call.
- Trusting model output as a command. A prompt-injection payload can produce text that looks like a valid instruction. Parse through a strict schema or sealed type and reject anything that does not match. Never call
Room.delete()based on raw model text. - Hardcoding a context window size. Model windows change with every release. Hardcoding 8192 or 32768 tokens means your trim logic breaks silently when the model is updated. Read the limit from a config or check the current docs.
- Storing history only in a StateFlow. The ViewModel survives rotation but not process death. The user loses the entire conversation. Mirror every turn to Room and reload it when the ViewModel is created.
- Dropping the system prompt during trim. The system prompt sets the model's role and constraints. If it lives in the history, trimming can remove it. Set it as
systemInstructionon the model instead. - Using the Chat object's internal history as the source of truth.
startChatkeeps its own list. If the ViewModel also keeps a list, the two drift. Pick one owner (the ViewModel) and pass a freshstartChat(trimmed)per call, or sync explicitly.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How does Firebase AI Logic startChat work, and where does the conversation state live?”
“How do you handle the context window limit in a long conversation?”
“What happens to chat state when the Android process is killed?”
“How do you prevent prompt injection from turning model output into a destructive command?”
Quiz
What does startChat(history) do in Firebase AI Logic?
A user's chat has 200 turns and the context window is exceeded. What is the simplest fix?
Why should you persist chat turns to Room instead of keeping them only in a StateFlow?
A model response contains the text {"action": "delete_all"}. What should the app do?
0 of 4 answered
Mini task
Exercise: Trim and persist a chat history (15 min)
-
Create a
ChatTurndata class withid: Long,role: Role(enum: USER, MODEL),text: String,timestamp: Long, andconversationId: String. -
Create a Room entity and DAO for
ChatTurn. The DAO must exposeinsert(turn)andobserveByConversation(id): Flow<List<ChatTurn>>ordered bytimestamp ASC. -
In a
ChatViewModel, keep aMutableStateFlow<List<ChatTurn>>. Oninit, collect the Room Flow into the StateFlow. -
Write a
trimHistory(turns: List<ChatTurn>, budgetTokens: Int): List<ChatTurn>function. Walk from the last turn backward, estimate tokens astext.length / 4 + 4, and stop when the running total exceeds the budget. Set the system prompt assystemInstructionon the model, not in the list. -
In a
send(text: String)function: calltrimHistoryon the existing turns, append the new user turn to the StateFlow and Room, build aList<Content>from the trimmed turns, callai.startChat(history).sendMessage(text), and append and save the model turn. -
Write a unit test: create 50 turns of 200 characters each, call
trimHistorywith a budget of 500 tokens, and assert that the result has fewer than 50 turns, always includes the newest turn, and the estimated total is under 500.
Done when: the test passes, the ViewModel compiles, and a manual run shows that after 50 turns the StateFlow list stays under the budget while Room still holds all 50 turns.