The agentic loop in 12 lines
An "agent" is a tool loop. Call the model, check for tool calls, execute them, append results, call again. Stop when the model returns text instead of more calls. That's it.
The shape of one iteration
- Send
contentsto the model. - If response has no
function_calls, returnresponse.text— done. - Otherwise: append the model's turn to
contents(so it remembers what it called). - Execute every function call (in parallel if independent).
- Append a single user turn containing all the function-response parts.
- Loop.
Parallel calls are normal
Modern Gemini models often emit multiple function_call parts in one turn. Execute them concurrently and return all results in one user turn — the API uses the id field to match results to calls.
You need a budget
Tool loops can run forever if the model keeps re-calling. Always bound iteration count and total elapsed time.