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
- Javascript
- Python
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
}
}
from google.genai import types
prompt = """
What is the sum of the first 50 prime numbers?
Generate and run code for the calculation, and make sure you get all 50.
"""
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=prompt,
config = types.GenerateContentConfig(
tools=[types.Tool(
code_execution=types.ToolCodeExecution
)]
)
)
for part in response.candidates[0].content.parts:
if part.text is not None:
display(Markdown(part.text))
if part.executable_code is not None:
code_html = f'{part.executable_code.code}' # Change code color
display(HTML(code_html))
if part.code_execution_result is not None:
display(Markdown(part.code_execution_result.output))
if part.inline_data is not None:
display(Image(data=part.inline_data.data, width=800, format="png"))
display(Markdown("---"))