Skip to main content

Using Gemini Code Execution

Gemini models can execute Python code to perform data analysis, create visualizations, and more. This is particularly useful for tasks like analyzing data files, generating charts, and running computational tasks.

See Live Demo for Code Execution

See Live Demo for a Data Analysis Agent built with Code Execution

const fileText = await readFileAsText(csvFile);
const genAI = new GoogleGenerativeAI(apiKey);
const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash",
tools: [
{
codeExecution: {},
},
],
});
// Generate content with code execution enabled
const result = await model.generateContent([
fileText,
"Generate and run data analysis code to analyze this CSV data, and make a relevant chart to demonstrate the key insights."
]);

// Process the response
const response = result.response;
for (const part of response.candidates[0].content.parts) {
// Handle executable code
if (part.executableCode) {
console.log("Code:", part.executableCode.code);
}

// Handle generated images (charts)
if (part.inlineData && part.inlineData.mimeType === 'image/png') {
const imageData = `data:image/png;base64,${part.inlineData.data}`;
// Display the image using your UI framework
}

// Handle code execution results
if (part.codeExecutionResult) {
const executionOutput = part.codeExecutionResult.output;
// Display execution results
}
}