How Code Execution works
mainBy enabling the CodeExecution tool, Gemini can generate and run code (like Python) to solve complex tasks. You can inspect the response parts to access the executableCode (the code generated) and the codeExecutionResult (the output of the execution).
use Gemini\Data\CodeExecution;
use Gemini\Data\Tool;
$response = $client
->generativeModel(model: 'gemini-2.0-flash')
->withTool(new Tool(codeExecution: CodeExecution::from()))
->generateContent('What is the sum of the first 50 prime numbers?');
foreach ($response->parts() as $part) {
if ($part->executableCode !== null) {
echo "Code: " . $part->executableCode->code . "\n";
}
if ($part->codeExecutionResult !== null) {
echo "Output: " . $part->codeExecutionResult->output . "\n";
}
}