Implement Function Calling
mainEnable the model to call custom functions by defining them as Tool objects containing FunctionDeclarations.
- Define the function's name, description, and parameters using a
Schema. - Attach the tool to the model using
withTool(). - When the model returns a
functionCallin a response part, execute your local logic and send the result back to the model usingsendMessage()with aContentobject containing aFunctionResponse.
// 1. Define the tool
$tool = new Tool(functionDeclarations: [
new FunctionDeclaration(
name: 'addition',
description: 'Performs addition',
parameters: new Schema(
type: DataType::OBJECT,
properties: [
'number1' => new Schema(type: DataType::NUMBER),
'number2' => new Schema(type: DataType::NUMBER),
],
required: ['number1', 'number2']
)
)
]);
// 2. Start chat with tool
$chat = Gemini::generativeModel(model: 'gemini-2.0-flash')->withTool($tool)->startChat();
$response = $chat->sendMessage('What is 4 + 3?');
// 3. Handle the call
if ($response->parts()[0]->functionCall !== null) {
$call = $response->parts()[0]->functionCall;
// ... execute local logic ...
$functionResponse = new Content(
parts: [new Part(functionResponse: new FunctionResponse('addition', ['answer' => 7]))],
role: Role::USER
);
$response = $chat->sendMessage($functionResponse);
}