Skip to content

Tool calling

Tool calling, also known as function calling, is a structured way to give LLMs the ability to make requests back to the application that called it. You define the tools you want to make available to the model, and the model will make tool requests to your app as necessary to fulfill the prompts you give it.

The use cases of tool calling generally fall into a few themes:

Giving an LLM access to information it wasn’t trained with

  • Frequently changing information, such as a stock price or the current weather.
  • Information specific to your app domain, such as product information or user profiles.

Note the overlap with retrieval augmented generation (RAG), which is also a way to let an LLM integrate factual information into its generations. RAG is a heavier solution that is most suited when you have a large amount of information or the information that’s most relevant to a prompt is ambiguous. On the other hand, if retrieving the information the LLM needs is a simple function call or database lookup, tool calling is more appropriate.

Introducing a degree of determinism into an LLM workflow

  • Performing calculations that the LLM cannot reliably complete itself.
  • Forcing an LLM to generate verbatim text under certain circumstances, such as when responding to a question about an app’s terms of service.

Performing an action when initiated by an LLM

  • Turning on and off lights in an LLM-powered home assistant
  • Reserving table reservations in an LLM-powered restaurant agent

If you want to run the code examples on this page, first complete the steps in the Getting started guide. All of the examples assume that you have already set up a project with Genkit dependencies installed.

This page discusses one of the advanced features of Genkit model abstraction, so before you dive too deeply, you should be familiar with the content on the Generating content with AI models page. You should also be familiar with Genkit’s system for defining input and output schemas, which is discussed on the Flows page.

At a high level, this is what a typical tool-calling interaction with an LLM looks like:

  1. The calling application prompts the LLM with a request and also includes in the prompt a list of tools the LLM can use to generate a response.
  2. The LLM either generates a complete response or generates a tool call request in a specific format.
  3. If the caller receives a complete response, the request is fulfilled and the interaction ends; but if the caller receives a tool call, it performs whatever logic is appropriate and sends a new request to the LLM containing the original prompt or some variation of it as well as the result of the tool call.
  4. The LLM handles the new prompt as in Step 2.

For this to work, several requirements must be met:

  • The model must be trained to make tool requests when it’s needed to complete a prompt. Most of the larger models provided through web APIs, such as Gemini and Claude, can do this, but smaller and more specialized models often cannot.
  • The calling application must provide tool definitions to the model in the format it expects.
  • The calling application must prompt the model to generate tool calling requests in the format the application expects.

Genkit provides a single interface for tool calling with models that support it. Each model plugin ensures that the last two of the above criteria are met, and the Genkit instance’s generate() function automatically carries out the tool calling loop described earlier.

Tool calling support depends on the model, the model API, and the Genkit plugin. Consult the plugin’s documentation to determine if tool calling is supported. Genkit forwards tools to the model plugin without checking support first, so a model that can’t call tools either rejects the request or ignores the tools, depending on the plugin and provider API.

Use @ai.tool() on an async def function to register a tool:

from genkit import Genkit
from genkit_google_genai import GoogleAI
from pydantic import BaseModel, Field
ai = Genkit(
plugins=[GoogleAI()],
model=GoogleAI.gemini('gemini-flash-latest'),
)
class GetWeatherInput(BaseModel):
location: str = Field(description='The location to get the current weather for')
@ai.tool()
async def get_weather(input: GetWeatherInput) -> str:
"""Gets the current weather in a given location."""
return f'The current weather in {input.location} is 63°F and sunny.'

The tool name defaults to the function name and the description defaults to the docstring (override either via name= and description= on @ai.tool()). Genkit derives the input and output schemas from the function’s type annotations. Tools must be async functions.

To read request context or stream progress chunks back to the caller, add a second ctx: ToolContext parameter (ctx.context, ctx.send_chunk(...)). To return media or extra content parts alongside structured data, return a MultipartToolResponse:

from genkit import MultipartToolResponse, Part, ToolContext
@ai.tool()
async def render_chart(input: GetWeatherInput, ctx: ToolContext[str]) -> MultipartToolResponse:
"""Renders a forecast chart for a location."""
ctx.send_chunk(f'Rendering chart for {input.location}...')
return MultipartToolResponse(
output={'location': input.location, 'status': 'rendered'},
content=[
Part.from_media(url='https://example.com/chart.png', content_type='image/png'),
],
)

Pass registered tools (or their names) to generate(), define_prompt(), or .prompt files. Control whether the model must call a tool via tool_choice ('auto', 'required', or 'none').

Using generate():

response = await ai.generate(
prompt='What is the weather in Baltimore?',
tools=[get_weather],
tool_choice='auto',
)

Using define_prompt():

weather_prompt = ai.define_prompt(
name='weatherPrompt',
tools=[get_weather],
prompt='What is the weather in {{location}}?',
)
response = await weather_prompt({'location': 'Baltimore'})

Using Prompt files:

---
tools: [get_weather]
input:
schema:
location: string
---
What is the weather in {{location}}?

Then execute the prompt in code:

# Assuming the prompt file is named weatherPrompt.prompt
weather_prompt = ai.prompt('weatherPrompt')
response = await weather_prompt({'location': 'Baltimore'})

When combining tool calling with streaming, chunks are ModelResponseChunk values. Read chunk.text for text deltas and inspect part.tool_request and part.tool_response on chunk.content:

result = ai.generate_stream(
prompt='What is the weather in Baltimore?',
tools=[get_weather],
)
async for chunk in result.stream:
if chunk.text:
print(chunk.text, end='', flush=True)
for part in chunk.content:
if part.tool_request is not None:
req = part.tool_request
print(f'\n[tool request] {req.name}({req.input})')
if part.tool_response is not None:
res = part.tool_response
print(f'\n[tool response] {res.name} -> {res.output}')
response = await result.response

Limiting tool call iterations with max_turns

Section titled “Limiting tool call iterations with max_turns”

Bound how many back-and-forth tool cycles ai.generate() runs in a single call with max_turns. The default limit is 50 turns. Lower it when you want tighter cost or latency budgets on multi-step agents:

Example: Web Research Agent

from pydantic import BaseModel, Field
class WebSearchInput(BaseModel):
query: str = Field(description='Search query')
@ai.tool()
async def web_search(input: WebSearchInput) -> str:
"""Search the web for current information."""
return f'Search results for "{input.query}": [relevant information here]'
response = await ai.generate(
prompt=(
'Research recent breakthroughs in fault-tolerant quantum computing, '
'key hardware approaches, and near-term applications.'
),
tools=[web_search],
max_turns=8,
)

Example: Portfolio Valuation

from typing import Literal
from pydantic import BaseModel, Field
class ArithmeticInput(BaseModel):
operation: Literal['add', 'subtract', 'multiply', 'divide']
a: float = Field(description='First operand')
b: float = Field(description='Second operand')
@ai.tool()
async def calculate(input: ArithmeticInput) -> float:
"""Perform exact arithmetic on two numbers."""
if input.operation == 'add':
return input.a + input.b
if input.operation == 'subtract':
return input.a - input.b
if input.operation == 'multiply':
return input.a * input.b
if input.b == 0:
raise ValueError('Division by zero')
return input.a / input.b
response = await ai.generate(
prompt=(
'Calculate the total value of 100 shares at $225.50, 50 shares at $178.20, '
'and 200 shares at $415.00, and compute the percentage weight of each position.'
),
tools=[calculate],
max_turns=12,
)

What happens when max_turns is reached?

ai.generate() does not raise an exception when it hits max_turns. Instead, it stops the loop and returns a ModelResponse with response.finish_reason == FinishReason.ABORTED and response.error set to a Failure with reason == ErrorReason.MAX_TURNS_EXCEEDED. All completed turns stay in response.messages, so you can inspect partial progress or continue the conversation in another ai.generate() call:

from genkit import ErrorReason
if response.error and response.error.reason == ErrorReason.MAX_TURNS_EXCEEDED:
print(f'Stopped after max_turns ({len(response.messages)} messages recorded)')

An exception raised inside a tool stops the tool loop. ai.generate() does not raise it. It returns a ModelResponse with finish_reason == FinishReason.FAILED and response.error.reason == ErrorReason.TOOL_FAILED. The model never sees the error and does not retry. response.messages drops the failed round and ends at the last completed one, so you can retry without re-running tools that already succeeded.

Raise PublicError or GenkitError to control the status and message. Any other exception is reported as INTERNAL with the message 'internal error', and Genkit logs the original traceback:

from genkit import ErrorReason, PublicError
from pydantic import BaseModel
class OrderInput(BaseModel):
order_id: str
@ai.tool()
async def lookup_order(input: OrderInput) -> str:
"""Looks up the delivery status of a restaurant order."""
raise PublicError('NOT_FOUND', f'No order {input.order_id}')
response = await ai.generate(prompt='Where is order A1?', tools=[lookup_order])
if response.error and response.error.reason == ErrorReason.TOOL_FAILED:
print(response.finish_reason, response.error.status, response.error.message)
# => failed NOT_FOUND No order A1

A model that calls a tool you didn’t register gets the same shape with NOT_FOUND and ErrorReason.TOOL_NOT_FOUND. See Error types for the full error model.

By default, Genkit repeatedly calls the LLM until every tool call has been resolved. You can conditionally pause execution in situations where you want to, for example:

  • Ask the user a question or display UI.
  • Confirm a potentially risky action with the user.
  • Request out-of-band approval for an action.

Interrupts halt the tool loop when a tool raises Interrupt(...) and return control to your caller so you can resume with interrupt.respond() or interrupt.restart(). Visit the interrupts guide to learn how to use them.

If you want full control over the tool-calling loop, set return_tool_requests=True. ai.generate() returns the model’s tool requests in response.tool_requests without running them, and you send back Part.from_tool_response(...) parts on the next turn:

from genkit import Message, Part, Role
response = await ai.generate(
prompt="What's the weather like in Baltimore?",
tools=[get_weather],
return_tool_requests=True,
)
while response.tool_requests:
tool_parts: list[Part] = []
for part in response.tool_requests:
req = part.tool_request
if req.name != 'get_weather':
raise ValueError(f'Unexpected tool: {req.name}')
output = await get_weather(GetWeatherInput.model_validate(req.input))
tool_parts.append(
Part.from_tool_response(
name=req.name,
output=output,
ref=req.ref,
)
)
response = await ai.generate(
messages=[
*response.messages,
Message(role=Role.TOOL, content=tool_parts),
],
tools=[get_weather],
return_tool_requests=True,
)

Use the genkit-mcp package (define_mcp_client or define_mcp_host) to connect to stdio Model Context Protocol (MCP) servers and expose their tools as Genkit tool actions:

from genkit_mcp import define_mcp_client
mcp_client = define_mcp_client(
ai,
'everything',
command='npx',
args=['-y', '@modelcontextprotocol/server-everything'],
)
response = await ai.generate(
prompt='Echo "hello".',
tools=[get_weather, 'everything:tool/*'],
)

MCP tools work alongside local @ai.tool() functions in the same ai.generate() request.