Function calling and tools
Why it matters
- Function calling is the bridge between a language model and your app's data. Without it the model can only guess; with it it can read your database, hit a REST endpoint, or trigger a side effect. Every AI feature that touches real data (search, booking, status lookup) needs this loop.
- Interviewers at senior level ask you to draw the full round-trip: model emits a function call, your code executes it, you send a function response back, the model continues. Getting the loop, the step limit, and the error path wrong is the most common reason AI features break in production.
- In Firebase AI Logic you declare functions with
FunctionDeclarationand pass them astoolswhen you create the model. For Claude, OpenAI, or any other provider the same loop runs on your backend, not in the app. Knowing which side owns the execution is a first-order design decision. - Tool output is untrusted model data. A prompt-injection attack can make the model call a destructive tool with attacker-supplied arguments. Validation and a step cap are not optional polish; they are the security boundary.
The simple explanation
- You are a receptionist at a hospital.
- A patient (the user) asks for a blood test.
- You (the model) cannot run the test yourself; you write a slip (a function call with JSON args) and hand it to the lab.
- The lab (your code) runs the test and writes the result on a second slip (a function response).
- You read the result and tell the patient the answer.
- If the patient asks for three tests, you loop: slip, lab, result, slip, lab, result. You cap the loop so a confused patient cannot keep the lab busy forever.
Function calling (also called tool use or tool calling) is a protocol where the model does not answer directly. Instead it emits a structured request: a function name and a JSON argument map. Your code executes that request and sends the result back. The model then produces the final natural-language answer.
The loop has three phases:
| Phase | Who acts | What moves |
|---|---|---|
| 1. Decide | Model | Emits a function call: name + args |
| 2. Execute | Your code | Runs the tool, returns a value |
| 3. Continue | Model | Receives the function response, may call again or answer |
In Firebase AI Logic you declare tools with FunctionDeclaration (name, description, a map of Schema parameters) and pass them as tools = listOf(Tool.functionDeclarations(...)) to generativeModel. Use a chat (startChat). The response's functionCalls list (of FunctionCallPart) tells you what to run. You execute each call, wrap the result in a FunctionResponsePart, and send it back with chat.sendMessage. Repeat until functionCalls is empty or you hit your own step limit (a small number like 3-5).
For Claude, OpenAI, or any non-Google provider the same loop runs on your backend. In the Anthropic Messages API the model returns tool_use blocks and you reply with tool_result blocks. The app calls your server; the server holds the API key, enforces auth and rate limits, calls the provider, executes tools, and streams the result back. See the Calling Claude and other LLM APIs through your backend lesson for the server side.
Key rules:
- Always cap the loop. A model that keeps calling the same tool will burn tokens and money.
- Validate every argument. The model can produce malformed JSON or values outside your schema. Treat tool arguments like user input.
- Never trust model output as a command. A prompt-injection payload can make the model call a delete tool. Validate and authorise on your side, and ask the user to confirm sensitive actions.
- Keep the tool list small and well-described. Vague descriptions cause the model to pick the wrong tool or hallucinate arguments.
Chat history and context limits interact here: every round-trip adds tokens. See Chat state, history and context limits for trimming strategy.
Notes
- In Firebase AI Logic a function call is a
FunctionCallPartwith aname(String) andargs(Map<String, JsonElement>). The model produces it; your code consumes it. It is not a method call on the model. - In Firebase AI Logic you pass
toolstogenerativeModel. The response'sfunctionCallsproperty is a list; it is empty when the model answers with text. - The loop is: send message → check
functionCalls→ execute → sendFunctionResponsePartback → check again. Cap it at a few iterations to prevent endless loops and token burn. - Tool arguments are untrusted. A prompt-injection attack can make the model emit a call to a destructive function with attacker-chosen arguments. Validate types, ranges, and permissions before executing.
- For non-Google providers (Claude, OpenAI) the tool loop runs on your backend. The app never sees the API key. The server calls the provider, executes tools, and streams the result. See the Calling Claude and other LLM APIs through your backend lesson.
- Each round-trip adds tokens to the context. Multiple tool calls increase the prompt size significantly. Trim or summarise old turns before the next call; see Chat state, history and context limits.
- Tool descriptions are the model's only documentation. A vague description like "get data" causes wrong-tool selection. Write descriptions the way you would write a Javadoc: state inputs, outputs, and side effects.
- A
FunctionResponsePartmust echo the original call'snameso the model can match the result to the request. Mismatched names confuse the model. - In production, log every tool call (name, args, result, latency) but redact PII. This is your primary debugging signal when a user reports a wrong answer.
- Streaming and function calling interact: if you stream the model's response (see Streaming AI responses in Compose), a function call can arrive in the stream. Wait until you have the whole call before running the tool.
Code example
This Kotlin snippet shows the function-calling loop with Firebase AI Logic: declare a tool, ask through a chat, run the returned calls, send the results back, and stop when the model is done or the step cap is hit.
import android.util.Log
import com.google.firebase.Firebase
import com.google.firebase.ai.ai
import com.google.firebase.ai.type.FunctionCallPart
import com.google.firebase.ai.type.FunctionDeclaration
import com.google.firebase.ai.type.FunctionResponsePart
import com.google.firebase.ai.type.GenerativeBackend
import com.google.firebase.ai.type.Schema
import com.google.firebase.ai.type.Tool
import com.google.firebase.ai.type.content
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.contentOrNull
// 1. Declare the tool the model may call
val weatherFn = FunctionDeclaration(
"getWeather",
"Return the current temperature and condition for one city.",
mapOf(
"city" to Schema.string("City name, for example Tokyo."),
"unit" to Schema.string("celsius or fahrenheit")
),
optionalParameters = listOf("unit")
)
// 2. Pass tools when you create the model. Read the model name from config.
fun buildModel(modelName: String) =
Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = modelName,
tools = listOf(Tool.functionDeclarations(listOf(weatherFn)))
)
fun errorJson(msg: String) = JsonObject(mapOf("error" to JsonPrimitive(msg)))
// 3. Run one call, validating args like user input
suspend fun runTool(call: FunctionCallPart): JsonObject = when (call.name) {
"getWeather" -> {
val city = (call.args["city"] as? JsonPrimitive)?.contentOrNull
if (city.isNullOrBlank() || city.length > 100) errorJson("invalid city")
else fetchWeather(city) // your own suspend function returning JsonObject
}
else -> errorJson("unknown tool: " + call.name)
}
// 4. The loop: chat, run tools, send results back, cap iterations
suspend fun ask(modelName: String, question: String): String? {
val chat = buildModel(modelName).startChat()
var response = chat.sendMessage(question)
val maxSteps = 5
var step = 0
while (response.functionCalls.isNotEmpty() && step < maxSteps) {
step++
// Run tools first (runTool suspends), then send every result back together.
val results = response.functionCalls.map { FunctionResponsePart(it.name, runTool(it)) }
response = chat.sendMessage(content { results.forEach { part(it) } })
}
if (response.functionCalls.isNotEmpty()) {
Log.w("AI", "Function-calling loop hit the step cap")
return null // show a fallback message instead
}
return response.text
}maxStepsstops a model that keeps asking for tools. Log when the cap is hit so you can spot it in production.call.argsis aMap<String, JsonElement>produced by the model. The safe castas? JsonPrimitivemeans a list or object where you expected a string becomes an error result, not a crash.- Each
FunctionResponsePartechoescall.nameso the model can match the result to its request. All calls from one response go back together. - Function calling is used through
startChatbecause the call and the result must travel back and forth in one conversation. - In a real app
askruns inside aviewModelScopecoroutine, so it is cancelled when the user leaves the screen.
Run the idea in plain Kotlin
data class FunctionCall(val name: String, val args: Map<String, String>)
data class FunctionResult(val name: String, val output: String)
// Simulates a model that decides whether to call a tool
fun modelDecide(userInput: String, history: List<FunctionResult>): FunctionCall? {
if (history.isEmpty() && userInput.contains("weather", ignoreCase = true)) {
return FunctionCall("get_weather", mapOf("city" to "Tokyo"))
}
return null // model is satisfied, no more calls
}
// Simulates the tool execution side
fun executeTool(call: FunctionCall): FunctionResult {
return when (call.name) {
"get_weather" -> FunctionResult(call.name, "22C, sunny")
else -> FunctionResult(call.name, "unknown tool: " + call.name)
}
}
fun main() {
val userInput = "What is the weather in Tokyo?"
var history = emptyList<FunctionResult>()
var step = 0
val maxSteps = 5
while (step < maxSteps) {
step++
val call = modelDecide(userInput, history)
if (call == null) break
val result = executeTool(call)
history = history + result
println("Step " + step + ": called " + call.name + " -> " + result.output)
}
if (step >= maxSteps) {
println("ERROR: exceeded max steps, possible infinite loop")
} else {
println("Final answer based on: " + history.last().output)
}
// Demonstrate the step cap catching a loop
println("---")
var loopHistory = emptyList<FunctionResult>()
var loopStep = 0
while (loopStep < maxSteps) {
loopStep++
// This model always calls the tool (simulated infinite loop)
val call = FunctionCall("get_weather", mapOf("city" to "Paris"))
val result = executeTool(call)
loopHistory = loopHistory + result
}
println("Loop cap hit at step " + loopStep + ", calls made: " + loopHistory.size)
}In production
- A support dashboard showed a spike in API spend over one night. No user-facing errors, but the billing alert fired.
- Logs revealed a single user session that triggered a large number of tool calls in a short window. The model kept calling
search_orderswith slightly different arguments and never converged. - The team had no step cap in the function-calling loop. The
whilecondition only checkedfunctionCalls.isNotEmpty().
- Added a hard
maxStepscap to the loop. When the cap is hit, the code logs a warning and returns a fallback message to the user. - Added a per-user rate limit on tool calls enforced on the backend before the model is even invoked.
- Added a unit test with a fake model that always returns a function call and asserts the loop terminates at
maxSteps. - Instrumented every tool call with a structured log line (user id, tool name, args hash, latency) so the next spike is traceable.
- Users reported a crash on a specific query. The stack trace showed a
ClassCastExceptioninside the tool executor. - The model returned
argswith acityfield that was a list instead of a string. The executor cast it to a string without checking.
- Replaced the cast with a safe cast (
as? JsonPrimitive). Wrong types now produce a function response with an error message instead of a crash. - Moved blocking tool work (disk, database) to
Dispatchers.IOso a slow tool never blocks the UI thread. - Added a schema-validation step: before executing, check that every
requiredfield is present and of the expected type. Log a warning when validation fails. - Wrote a fuzz test that feeds random argument maps to the executor and asserts no exception escapes.
Common mistakes
- No step cap on the function-calling loop. A model that keeps emitting function calls can loop for a long time, burning tokens and money. Always wrap the loop in a
while (step < maxSteps)guard and log when the cap is hit. - Trusting call.args without validation. The model can produce malformed JSON, wrong types, or attacker-injected values via prompt injection. Treat every argument like user input: check type, range, and permission before executing.
- Running tool execution on the main thread. A network call or database query inside the tool executor blocks the UI. Run it in a
Dispatchers.IOcoroutine or on a background thread, and cancel it withviewModelScopewhen the user leaves. - Vague tool descriptions. The model picks a tool based on its description. A description like "get data" causes wrong-tool selection and hallucinated arguments. Write descriptions that state inputs, outputs, and side effects, like a Javadoc.
- Forgetting to echo the call name in the response. A
FunctionResponsePartmust carry the samenameas the original call. If you hard-code a different name, the model cannot match the result. - Calling a non-Google LLM with a secret key in the app. An API key in
BuildConfigor a string literal is extractable from the APK. The app must call your own backend, which holds the key, enforces auth and rate limits, and calls the provider. See the Calling Claude and other LLM APIs through your backend lesson.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“Explain the function-calling loop in an AI app.”
“How do you prevent a prompt-injection attack through tool arguments?”
“What happens when the model returns multiple function calls in one response?”
“How does function calling interact with streaming in Compose?”
Quiz
What does the model return when it decides to use a tool?
Why must you cap the number of function-calling iterations?
Where should the API key for a non-Google LLM (Claude, OpenAI) live?
What must a function response include so the model can match it to the original call?
0 of 4 answered
Mini task
15-minute exercise: build a two-step tool loop
You will simulate a function-calling loop in a plain Kotlin file (no Android dependencies) and then sketch how it maps to Firebase AI Logic.
-
Create a
ToolExecutorobject with two functions:getBalance(accountId: String): Stringandtransfer(from: String, to: String, amount: Double): String. Each returns a plain-text result string. Add a guard: ifamountis negative, return an error string instead of executing. -
Write a
runLoopfunction that takes a user question string and a list of tool names. It should:- Simulate the model by checking: if the question contains "balance", call
getBalance; if it contains "transfer", calltransfer. - Execute the tool, print the result, and loop once more to check for a second call.
- Cap the loop at 3 iterations. Print a warning if the cap is hit.
- Simulate the model by checking: if the question contains "balance", call
-
Add a validation step: before calling
transfer, check thatfromandtoare non-empty andamountis positive. If validation fails, print the error and stop the loop. -
Run the program with three inputs:
"What is my balance?"→ should callgetBalanceonce and stop."Transfer 50 to Alice"→ should calltransferonce and stop."Transfer -10 to Alice"→ should hit the validation guard and stop without executing.
-
Sketch the Firebase mapping in a comment block: replace the
when-based simulation with a model created withtools = listOf(Tool.functionDeclarations(...)), callchat.sendMessage(question), checkresponse.functionCalls, execute, and send back aFunctionResponsePart. Note where you would addviewModelScopecancellation and a user confirmation fortransfer.
Done condition: the program prints the expected output for all three inputs, the negative-amount case is rejected, and the comment block names the three Firebase AI Logic types (FunctionDeclaration, FunctionCallPart, FunctionResponsePart) and the step-cap variable.