How the tool loop works
1
Send prompt + tools
Your code calls
ai.generate() with a list of available tools.2
Model requests a tool
The model returns a
toolRequest part instead of (or alongside) text.3
Genkit executes the tool
Genkit finds the tool by name, validates the input, and calls your function.
4
Tool result fed back
The tool’s return value is added to the message history as a
toolResponse part.5
Model continues
The model sees the tool result and either calls another tool or returns its final answer.
maxTurns is reached.
Basic agent example
The following example shows a simple research agent with two tools: a web search tool and a calculator.Defining tools
Tools are defined withai.defineTool(). Each tool has a name, description, input schema, output schema, and an implementation function:
maxTurns — limiting iterations
The maxTurns option caps the number of tool-calling rounds. The default is 5. If the model has not finished within maxTurns iterations, generate() throws a GenkitError.
Inspecting tool calls
After agenerate() call completes, you can inspect which tools were called using response.toolRequests. This is useful for logging, debugging, and building audit trails:
response.toolRequests only contains tool requests from the final model message. To see all tool calls across all turns, inspect response.messages.Forcing tool use with toolChoice
By default, the model can choose whether to call tools. Set toolChoice: 'required' to force the model to call at least one tool, or toolChoice: 'none' to disable tool calls even if tools are listed:
'auto'(default) — model decides whether to call tools.'required'— model must call at least one tool.'none'— model must not call any tools.
Returning tool requests manually
SetreturnToolRequests: true to stop the automatic tool call loop and handle tool execution yourself. This gives you full control over how tools are invoked:
Interrupt pattern (human-in-the-loop)
Genkit supports a formal interrupt mechanism for workflows that require human approval or input before a tool runs. Useai.defineInterrupt() to mark a tool as interruptible:
Multi-tool agent in Go
Tools
Learn how tools are defined and resolved.
Flows
Wrap agents in observable, deployable flows.
Structured output
Return typed results from agent runs.
Sessions
Persist agent conversation history across requests.
