AI chat assistant with streaming and tool calling

Build a streaming AI chat app in Jetpack Compose with Firebase AI Logic, App Check, Room history, tool calling, and markdown rendering in Kotlin. About 32 hours.

What you will build

The finished app is a full-screen chat interface built in Jetpack Compose. The user types a message and the model's answer streams into the screen chunk by chunk. A stop button cancels the in-flight stream. Chat history persists in Room and is trimmed before each request so it fits the model's context window. Two declared functions let the model read the device's local time or search the user's saved notes. Answers render as markdown. Error, quota, and offline states show a retry button. A second repository talks to your own backend for providers such as Claude, streaming tokens back with server-sent events. This project shows an employer you can handle async streaming, cancellation, persistence, and multi-step AI orchestration in a real Android app. It also shows you understand where secrets belong (never in the APK) and how to keep the UI responsive while text keeps arriving.

Skills you practise

  • Streaming Flow collection in Compose with a cancellable Job
  • Tool-calling loop with a step limit and error recovery
  • Room persistence with context-window trimming
  • Unidirectional data flow through a StateFlow UI state
  • Server-sent events through a Ktor client for your own backend
  • Markdown rendering without blocking the main thread
  • App Check protection for AI requests

Architecture

The app follows unidirectional data flow. The Compose UI observes a StateFlow<ChatUi> exposed by ChatViewModel. ChatUi carries the message list, the streaming reply, a streaming flag, and the current error. The ViewModel launches each send in viewModelScope and keeps the Job so the stop button can cancel it. The repository wraps Firebase AI Logic: Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(...) with the tool declarations, then startChat(history) with the trimmed history loaded from Room, then sendMessageStream, which returns a Flow<GenerateContentResponse>. Text chunks are appended to the UI state; if the model asks for function calls, the app runs them, sends a FunctionResponsePart for each, and streams again, up to a fixed step limit. Room stores every finished message. App Check runs on every request so only your genuine app can reach the backend through your Firebase project. For other providers, a second repository reads server-sent events from your own server, which holds the provider API key. No provider API key ever ships in the app.

Module or layerResponsibility
UI (Compose)Renders the chat list, input bar, stop button, and error and offline states. Collects StateFlow<ChatUi> and sends user intents to the ViewModel.
ViewModelHolds ChatUi, owns the streaming Job, maps errors to UI state, and calls the repository. Exposes one StateFlow as the source of truth.
RepositoryBuilds the Firebase AI Logic model and chat, runs the streaming and tool-calling loop, and trims history. Exposes the same interface for the SSE backend.
Room (persistence)Stores ChatMessage and SavedNote entities. DAOs for insert, query, and search. All access is from suspend functions off the main thread.
Tool registryHolds the function declarations (local time, note search). Validates arguments, runs a call by name, and returns a JSON result or a JSON error.
Backend adapter (optional)For Claude or other providers: a small server you run. It holds the API key, calls the provider, and streams the reply back as server-sent events. The app talks to it through Ktor.

Milestones

1. Project scaffold, Firebase AI Logic and App Check

Get a blank Compose app that streams a reply from the Gemini Developer API through Firebase AI Logic, with App Check installed.

  1. Create a Compose project, connect it to a Firebase project, enable Firebase AI Logic with the Gemini Developer API in the console, and add google-services.json to the app module.
  2. Add the Firebase BoM with the firebase-ai and App Check (firebase-appcheck-playintegrity, plus firebase-appcheck-debug for debug builds) libraries.
  3. In Application.onCreate, install the App Check provider factory before any AI call: Play Integrity in release, the debug provider in debug builds, and register the debug token in the console.
  4. Create a ChatRepository interface with a send function that returns a Flow of text, and implement it with Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(modelName), startChat, and sendMessageStream. Read the model name from Remote Config or a constant you can change.
  5. Never put a Gemini API key in the app. Firebase AI Logic calls the model through your Firebase project, and App Check limits that access to your genuine app.

Done when: A debug build streams a reply into Logcat chunk by chunk, and the App Check metrics in the Firebase console show the requests as verified.

Lessons: gemini in your app with firebase ai logic, storing secrets and the keystore

2. Chat UI with StateFlow and Compose

Render a scrollable message list and an input bar that update from a single StateFlow<ChatUi>.

  1. Define ChatUi as a data class with messages, reply, isStreaming, and error.
  2. Create a ChatViewModel that exposes val ui: StateFlow<ChatUi>. Use a private MutableStateFlow and update for every write.
  3. Build the screen: a LazyColumn with stable keys for messages, a TextField for input, and a send button that calls viewModel.send(text).
  4. Collect the state in the composable with collectAsStateWithLifecycle.
  5. Add a LaunchedEffect keyed on the message count and reply length that scrolls to the bottom as text arrives.

Done when: Sending a message shows the user bubble and an assistant bubble that grows as chunks arrive. Rapid sends do not crash or interleave replies.

Lessons: viewmodel and ui state, stateflow and sharedflow, thinking in compose

3. Streaming collection and stop button

Collect the Flow from sendMessageStream, append text to the UI state, and cancel the stream when the user taps stop.

  1. In the ViewModel, launch the collection in viewModelScope and keep the returned Job. Disable send while a job is active.
  2. Inside collect, append response.text (skip chunks where it is null) with _ui.update.
  3. Add a stop() function that calls job?.cancel(). The stop button calls viewModel.stop().
  4. In a finally block, set isStreaming = false and clear the job. Rethrow CancellationException instead of showing it as an error.
  5. Test: start a long answer, tap stop mid-stream, and confirm no more text appears and the partial reply is kept.

Done when: Tapping stop ends the stream, no more chunks are appended, the stop does not show an error, and send is enabled again.

Lessons: streaming ai responses in compose, structured concurrency and cancellation, collecting flows safely in the ui

4. Room persistence and context-window trimming

Save every message to Room and trim the oldest turns before each request so the history fits the model's context window.

  1. Define ChatMessage (role, text, timestamp) and SavedNote entities, with DAOs for insert, ordered query, and note search.
  2. Persist the user message before the request and the assistant message once the stream completes or is stopped, not once per chunk.
  3. Before each request, load messages from Room, drop the oldest turns until the history fits your budget (estimate with model.countTokens or a conservative character count), and map the rest to content(role = "user") and content(role = "model") for startChat(history = ...).
  4. Keep user and model turns paired when trimming, so the history never starts with an orphaned model reply.
  5. Write a unit test for the pure trimming function: feed it a long history and assert the result fits the budget and keeps the newest turns.

Done when: After a long conversation, the request history contains only the newest turns that fit the budget, the conversation survives an app restart, and the trim test passes.

Lessons: room entities daos queries, chat state history and context limits, single source of truth

5. Tool-calling loop with a step limit

Declare two functions (local time, note search) and run a loop that executes them when the model asks, up to a fixed number of steps.

  1. Declare each tool with FunctionDeclaration(name, description, parameters) using Schema types, and pass tools = listOf(Tool.functionDeclarations(listOf(...))) to generativeModel.
  2. Implement getLocalTime (returns the device time and time zone) and searchNotes (queries Room for matching SavedNote rows). Validate arguments such as the search query like any user input.
  3. While collecting a stream, gather response.functionCalls. When the stream ends with calls, run each one and send a FunctionResponsePart(call.name, resultJson) for each back in one message with sendMessageStream.
  4. Cap the loop with maxSteps. If the cap is hit, stop and show a short fallback message instead of looping.
  5. Wrap each tool run in try/catch (rethrowing CancellationException) and send a JSON error as the function response so the model can explain the failure.

Done when: Asking "what time is it?" triggers the tool and the answer includes the time. Asking to search notes returns matching rows. The loop never exceeds the step cap.

Lessons: function calling and tools, error handling and result types

6. Markdown rendering and error and offline states

Render assistant answers as markdown and show retry UI for quota, network, and offline errors.

  1. Add a markdown renderer (for example a Compose markdown library, or Markwon in an AndroidView). Throttle re-rendering while streaming and do any heavy parsing on Dispatchers.Default.
  2. Map errors to user-readable states: QuotaExceededException and other FirebaseAIException subclasses from com.google.firebase.ai.type, and network failures.
  3. Show a retry button when error is set. Retry re-sends the last user message.
  4. Watch connectivity with ConnectivityManager.NetworkCallback, disable send while offline, and show a banner.
  5. Report unexpected exceptions from the tool loop to your crash reporter, without logging the user's messages.

Done when: A long answer with headings and bullet points renders as formatted markdown without visible jank. A simulated quota error shows a working retry button. Going offline disables send and shows a banner.

Lessons: latency cost and fallbacks, crash handling and reporting, privacy safety and content filtering

7. Alternative backend path with server-sent events

Add a second repository that talks to your own server for Claude or other providers, streaming back with server-sent events.

  1. Write a small server that authenticates your app's users, holds the provider API key in its environment, calls the provider's streaming API, and forwards the text to the app as SSE.
  2. In the app, use the Ktor client's SSE support to connect to your endpoint and turn each event's data into a text chunk.
  3. Create SseChatRepository implementing the same ChatRepository interface, so the ViewModel does not change.
  4. Choose the backend with a build flag or a Remote Config switch.
  5. Confirm the provider key exists only on the server: the app sends a user session token, never a provider key.

Done when: Switching to the SSE backend streams text from your server into the same UI. The provider key is absent from the app's source and APK. Stop also cancels the SSE request.

Lessons: calling claude and other llm apis through your backend, ktor client

Key code

import com.google.firebase.ai.Chat
import com.google.firebase.ai.type.Content
import com.google.firebase.ai.type.FunctionCallPart
import com.google.firebase.ai.type.FunctionResponsePart
import com.google.firebase.ai.type.content
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
 
interface ToolRegistry {
    suspend fun run(call: FunctionCallPart): JsonObject
}
 
data class ChatUi(
    val reply: String = "",
    val isStreaming: Boolean = false,
    val error: String? = null,
    val stoppedEarly: Boolean = false,
)
 
// One user turn: stream text, run requested tools, stream again, capped at maxSteps.
suspend fun streamTurn(
    chat: Chat, // from model.startChat(history = trimmedHistory)
    userText: String,
    ui: MutableStateFlow<ChatUi>,
    tools: ToolRegistry,
    maxSteps: Int = 5,
) {
    var next: Content = content { text(userText) }
    var step = 0
    ui.update { it.copy(reply = "", isStreaming = true, error = null, stoppedEarly = false) }
    try {
        while (true) {
            val calls = mutableListOf<FunctionCallPart>()
            chat.sendMessageStream(next).collect { chunk ->
                chunk.text?.let { t -> ui.update { it.copy(reply = it.reply + t) } }
                calls += chunk.functionCalls
            }
            if (calls.isEmpty()) break // plain text answer: done
            if (++step > maxSteps) {
                ui.update { it.copy(stoppedEarly = true) }
                break
            }
            val results = calls.map { call ->
                val json = try {
                    tools.run(call)
                } catch (e: CancellationException) {
                    throw e
                } catch (e: Exception) {
                    JsonObject(mapOf("error" to JsonPrimitive(e.message ?: "tool failed")))
                }
                FunctionResponsePart(call.name, json)
            }
            next = content { results.forEach { part(it) } }
        }
    } finally {
        ui.update { it.copy(isStreaming = false) }
    }
}
  • The ViewModel calls streamTurn inside viewModelScope.launch and keeps the Job; cancelling it cancels the collect, which cancels the underlying streaming request. Other exceptions propagate so the ViewModel can map QuotaExceededException and friends to UI state.
  • Function calls can arrive in any chunk, so they are gathered during collect and handled after the stream ends. You cannot continue an outer loop from inside the collect lambda.
  • All results from one round go back together in a single content { part(...) } message, and Chat adds every turn to its own history automatically.
  • A failing tool returns a JSON error instead of throwing, so the model can tell the user what went wrong. CancellationException is rethrown so stop still works.

Pitfalls

  • Stop updates the UI but the collection keeps running. If the stop button only flips a flag, chunks keep arriving and the request keeps using quota. Fix: cancel the Job that runs collect; cancelling the collector cancels the streaming request. Also rethrow CancellationException so it is not shown as an error.
  • History grows until the request fails. Sending the full stored conversation every time eventually exceeds the context window or gets slow and expensive. Fix: trim the oldest turns to a token budget before startChat, keep user and model turns paired, and unit test the trimming function.
  • A tool exception kills the turn. An exception from a tool escapes the loop, the model never gets a function response, and the chat is left half-finished. Fix: catch tool failures and send a JSON error as the FunctionResponsePart, while still rethrowing CancellationException.
  • Re-parsing markdown on the main thread for every chunk. Each chunk triggers a full parse of a growing string, which causes dropped frames on long answers. Fix: throttle re-rendering while streaming, parse heavy content on Dispatchers.Default, and render the final text once the stream ends.
  • App Check installed too late or never enforced. If the provider factory is installed after the first AI call, early requests go out without a valid token; if enforcement is never turned on, anyone with your Firebase config can call the model through your project. Fix: install App Check in Application.onCreate, watch the metrics, then enforce it for Firebase AI Logic.
  • Writing to Room for every streamed chunk. Persisting each chunk adds a database write per token-sized update for no benefit. Fix: keep the partial reply in the UI state and write the assistant message once, when the stream completes or the user stops it.

Code review finding

Tool execution failure leaves the chat in a broken state
  • The model returns a function call, the tool throws, and the exception propagates out of the loop, ending the turn.
  • The user sees a half-rendered assistant bubble with no error message and no way to retry.
  • Room has the user message but no assistant reply, so the next turn's history starts with two user turns in a row.
The fix
  • Catch failures around each tool run and send a JSON error as the FunctionResponsePart, so the model can produce a user-facing answer; rethrow CancellationException.
  • Persist the partial assistant text (or a short error note) when the turn ends for any reason, so history stays paired.
  • Add a unit test with a fake ToolRegistry that throws IllegalStateException, and assert the loop sends an error response and finishes.
  • Show a retry button that re-sends the last user message when ChatUi.error is set.

Stretch goals

  • Add a conversation list screen backed by Room, with Paging 3 for long histories.
  • Turn on limited-use App Check tokens for Firebase AI Logic and read how they change replay protection.
  • Add screenshot tests for the error and offline states.
  • Add a baseline profile for the chat screen and measure jank with Macrobenchmark during a long streamed answer.
  • Add an input check that blocks obviously sensitive data before it is sent to the model.

Done checklist

  • The stop button cancels the collecting coroutine; no chunks are appended after stop and stop is not shown as an error.
  • Room stores every user and assistant message, and the request history is trimmed to a budget with paired turns.
  • The tool-calling loop uses FunctionDeclaration, Tool.functionDeclarations, and FunctionResponsePart, respects maxSteps, and survives a throwing tool.
  • Markdown renders without visible jank during a fast stream.
  • App Check is installed before the first AI call and enforced for Firebase AI Logic. No provider API key exists in the app source or APK.
  • Quota, network, and offline errors show a clear message, and retry re-sends the last message.
  • The SSE backend path works end to end and the provider key lives only on your server.
  • Unit tests cover the trimming function, the tool loop with a throwing tool, and cancellation.

Talking about it in an interview

  • Explain why you chose a single StateFlow as the source of truth instead of several LiveData or SharedFlow streams. Mention the trade-off: one state object is simple to test, but frequent streamed updates mean you should keep list items keyed and stable to avoid extra recomposition.
  • Walk through the tool-calling loop and the step limit. Explain that without the cap a model could keep requesting tools and burn quota, and describe how a failing tool becomes a JSON error the model can explain.
  • Describe the context-window trimming strategy: oldest turns go first, user and model turns stay paired, and the budget is estimated with token counts. Mention the trade-off that trimming loses early context, and that a running summary could fix that later.
  • Talk about the backend path. Explain that a provider key in an APK can be extracted, so the key lives on your server, which authenticates users, applies limits, and streams back over SSE. The same pattern works for any provider.
  • Explain the cancellation design: the job runs in viewModelScope, so it survives configuration changes and is cancelled when the ViewModel is cleared, and the stop button cancels it directly. Cancelling the collector cancels the network request too.