Calling Claude and other LLM APIs through your backend

Learn how an Android app calls Claude or OpenAI through your backend in Kotlin, streams SSE with OkHttp, and runs tool-call loops with a step limit. About 25 minutes.

Why it matters

  • Cloud LLM APIs like the Anthropic Messages API and OpenAI authenticate with a secret API key. Shipping that key in the APK means anyone can extract it with a decompiler and burn your quota.
  • Interviewers ask you to draw the full request path: app → your backend → provider, and to explain where auth, rate limiting, and quota enforcement live.
  • Streaming with server-sent events and collecting the result in a Compose StateFlow is the pattern you will build in almost every AI feature. Getting the cancellation and back-pressure wrong causes memory leaks and stale UI.
  • Tool calling (function calling) is supported by the major providers. Knowing the loop, the step limit, and where tool execution happens separates a mid answer from a senior one.

The simple explanation

  • You are the customer at a restaurant. You never see the kitchen (the LLM provider) or the chef's knife (the API key).

The core rule: never put an LLM API key in the APK. The key lives on your backend. The Android app sends a request to your server; the server adds the key, calls the provider (Anthropic Messages API, OpenAI, or any other), and streams the response back.

On the Android side you read the stream with OkHttp or Ktor. A common choice is server-sent events (SSE): text lines like event: ... and data: ..., with a blank line between events. Your backend decides the event shape and the end marker (OpenAI-style streams end with data: [DONE]; the Anthropic Messages API sends a message_stop event). You wrap the read loop in a Kotlin Flow so Compose can collect it.

For tool calling (function calling), the model returns a request naming a tool and its JSON arguments. In the Anthropic Messages API this is a tool_use content block (with stop_reason set to tool_use); you run the tool and send back a tool_result block in the next user message. This repeats until the model returns plain text or you hit your own step limit (a small number like 3-5). Without the limit a buggy tool can loop for a long time.

ConcernWho handles it
API key storageBackend server only
Auth / rate limit / quotaBackend
SSE parsingAndroid (OkHttp / Ktor)
Tool executionBackend or app, with step cap
Chat history + context trimViewModel + Room
UI rendering of partial textCompose StateFlow

If you use Firebase AI Logic for Gemini, the key-less client SDK handles the proxy for you. For Claude, OpenAI, or any other provider you must build the backend yourself. Check the current docs for supported models and devices.

Notes

  • The LLM API key must live on the backend server. Never put it in BuildConfig, res/raw, AndroidManifest metadata, or any file inside the APK.
  • SSE format: each event has data: lines (and an optional event: line), ended by a blank line. Agree on an end marker with your backend (for example data: [DONE]) and also stop when readLine() returns null, which means the server closed the stream.
  • Wrap the OkHttp read loop in a Flow and shift to Dispatchers.IO so the blocking readLine() call never touches the main thread.
  • Collect the Flow inside viewModelScope so the stream cancels automatically when the ViewModel is cleared (user leaves the screen).
  • A tool-call loop must have a hard step limit (a few iterations). Without it a model that keeps requesting a tool will loop until the provider rate-limits or the user's quota is exhausted.
  • Store chat history in Room and trim or summarise old turns before the token count approaches the context window. Never send the full unbounded history.
  • Validate and sanitise model output before acting on it. Model text can contain prompt injection; treat it as untrusted input, not as a command.
  • For Gemini specifically, Firebase AI Logic gives you a client SDK with no Gemini key in the app, protected by App Check. For Claude, OpenAI, or any other provider you build the backend yourself.
  • Never let a tool call do something sensitive (pay, delete, send) without the user confirming in the app. Tool results and fetched pages can carry prompt injection.
  • Render partial markdown in Compose safely (use a markdown renderer that escapes HTML) to avoid injection through the model's output.
  • Check the current provider docs for model names and context window sizes. These change often.

Code example

This shows the Android side: a repository that calls your backend's SSE endpoint with OkHttp and a ViewModel that collects the chunk stream into a StateFlow for Compose. The backend here sends one text chunk per data: line and ends with data: [DONE].

import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
 
data class ChatTurn(val role: String, val content: String)
data class ToolSpec(val name: String, val schema: String)
data class ChatPayload(val history: List<ChatTurn>, val tools: List<ToolSpec>) {
    fun toJson(): String = "{}" // Placeholder for serialization
}
 
class ChatError(val code: Int) : Exception("HTTP $code")
 
object TokenStore {
    fun get(): String = "dummy_token" // In production, fetch from secure storage
}
 
data class ChatUiState(
    val history: List<ChatTurn> = emptyList(),
    val partial: String = ""
)
 
// App calls YOUR backend; the backend holds the LLM API key.
class ChatRepository(
    private val client: OkHttpClient,
    private val baseUrl: String
) {
    fun streamCompletion(
        history: List<ChatTurn>,
        tools: List<ToolSpec> = emptyList()
    ): Flow<String> = flow {
        val json = ChatPayload(history, tools).toJson()
        val req = Request.Builder()
            .url("$baseUrl/api/chat/stream")
            .post(json.toRequestBody("application/json".toMediaType()))
            .header("Authorization", "Bearer ${TokenStore.get()}")
            .build()
 
        client.newCall(req).execute().use { resp ->
            if (!resp.isSuccessful) throw ChatError(resp.code)
            val stream = resp.body?.byteStream() ?: throw ChatError(502)
            val reader = stream.bufferedReader()
            var line = reader.readLine()
            while (line != null) {
                currentCoroutineContext().ensureActive() // stop if the collector was cancelled
                if (line.startsWith("data: ")) {
                    val chunk = line.removePrefix("data: ").trim()
                    if (chunk == "[DONE]") break
                    emit(chunk)
                }
                line = reader.readLine()
            }
        }
    }.flowOn(Dispatchers.IO)
}
 
// ViewModel: collect chunks, cancel on leave
class ChatViewModel(private val repo: ChatRepository) : ViewModel() {
    private val _ui = MutableStateFlow(ChatUiState())
    val ui: StateFlow<ChatUiState> = _ui
 
    fun send(text: String) {
        viewModelScope.launch {
            repo.streamCompletion(_ui.value.history).collect { chunk ->
                _ui.update { it.copy(partial = it.partial + chunk) }
            }
        }
    }
}
  • resp.body?.byteStream() ?: throw handles the nullable ResponseBody in OkHttp 4.x without a force-unwrap crash.
  • readLine() blocks, so the flow runs on Dispatchers.IO, and ensureActive() stops the loop between lines after cancellation. Closing the response (the use block) releases the connection.
  • toJson() is a placeholder; use kotlinx.serialization or Moshi in a real app. The backend, not the app, adds the provider key.

Run the idea in plain Kotlin

// Simulates the tool-call loop: model returns a tool call,
// the server executes it, sends the result back, repeats with a step limit.

data class ToolCall(val name: String, val args: String)
data class LlmResponse(val text: String, val toolCall: ToolCall?)

class FakeLlmBackend {
  private var step = 0
  fun respond(history: List<String>): LlmResponse {
      step++
      if (step == 1) {
          return LlmResponse("", ToolCall("get_weather", "{\"city\":\"Paris\"}"))
      }
      if (step == 2) {
          return LlmResponse("It is 18 degrees in Paris.", null)
      }
      return LlmResponse("No more steps.", null)
  }
}

fun executeTool(name: String, args: String): String {
  return "weather_result_for_" + name + "_" + args
}

fun main() {
  val backend = FakeLlmBackend()
  val history = mutableListOf<String>()
  var fullText = ""
  var steps = 0
  val maxSteps = 5

  while (steps < maxSteps) {
      val resp = backend.respond(history)
      fullText += resp.text
      steps++
      if (resp.toolCall == null) break
      val result = executeTool(resp.toolCall.name, resp.toolCall.args)
      history.add(result)
  }

  println("Final text: " + fullText)
  println("Steps used: " + steps)
  println("History size: " + history.size)
}

In production

API key leaked via BuildConfig
  • A team stored the Anthropic API key in a Gradle property and exposed it through BuildConfig.
  • Soon after release the key was extracted from a decompiled APK and used by strangers.
  • The provider dashboard showed a spike in requests and the monthly quota was exhausted before the team noticed.
The fix
  • Rotated the key immediately and moved all provider calls behind a backend endpoint.
  • Added a CI check that greps the built APK for known key prefixes and fails the build if found.
  • For the Gemini path they switched to Firebase AI Logic with App Check so no key ships in the client at all.
Uncancelled stream after navigation
  • A chat screen collected the SSE Flow inside lifecycleScope instead of viewModelScope.
  • When the user navigated away the OkHttp call kept running, the StateFlow kept emitting into a dead composable, and the next visit showed stale partial text.
  • Memory profiling showed growing BufferedInputStream objects that were never closed.
The fix
  • Moved collection into viewModelScope so the coroutine cancels when the ViewModel is cleared.
  • Added an explicit cancel() on the flow collector and cleared partial in onCleared().
  • Added a unit test with a fake OkHttpClient that returns a canned SSE body and asserts the collector stops after cancellation.

Common mistakes

  • API key in BuildConfig or res/raw. Any key inside the APK is extractable with a decompiler. It must stay on the backend server, never in app code or resources.
  • Calling the LLM provider directly from the app. You lose auth, per-user rate limiting, and quota control. The backend is the only layer that can enforce all three before the request reaches the provider.
  • No clear end of stream. If the backend keeps the connection open and never sends an end marker, the reader waits on readLine() and the spinner never stops. Agree on an end event, stop on it, and also handle readLine() returning null and a read timeout.
  • No step limit on the tool-call loop. A model that keeps requesting a tool will loop until the provider rate-limits or the user's quota is exhausted. Cap iterations at a small number and alert when the cap is hit.
  • Collecting the stream outside viewModelScope. The OkHttp call survives navigation, leaks memory, and emits into a dead composable. Always collect inside viewModelScope so cancellation is automatic.
  • Trusting model output as a command. Model text can contain prompt injection. Validate and sanitise before acting on it; treat all model output as untrusted input.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“Why can't an Android app call the Anthropic Messages API or OpenAI API directly?”

“How do you stream an LLM response into a Jetpack Compose UI?”

“Explain the tool-call or function-calling loop.”

“How do you manage chat history and context limits?”

Quiz

Why can't an Android app call the Anthropic Messages API directly?

Your backend streams SSE and ends with data: [DONE]. What does that line tell the app?

In a tool-call loop, what prevents infinite recursion?

Where should the LLM API key live in a production Android app?

0 of 4 answered

Mini task

15-minute exercise: SSE stream collector with a step-limited tool loop

  1. Create a new Kotlin file ToolLoop.kt in a src/main/kotlin package.
  2. Define a data class ToolCall(name: String, args: String) and a data class LlmResponse(text: String, toolCall: ToolCall?).
  3. Write a function runToolLoop(backend: (List<String>) -> LlmResponse, maxSteps: Int = 5): String that calls backend in a loop, accumulates text, executes any toolCall by appending a placeholder result to the history, and stops when toolCall is null or maxSteps is reached.
  4. Write a fun main() that passes a lambda returning a ToolCall on the first call and plain text on the second, then prints the accumulated text and the number of steps used.
  5. Run the file with kotlinc ToolLoop.kt -include-runtime -d tool.jar && java -jar tool.jar (or in an IDE).

Done when: the program prints the final text, the step count is 2, and the history contains exactly one tool result. If the step count is 5, your loop is not breaking on a null toolCall.

Next: Streaming AI responses in Compose