Anyone tried running Python code as a

Anyone tried running Python code as a Genkit tool?
I’m experimenting with letting my chartAgent call a pythonExecutor tool to do data transformations. Here’s a mini snippet:

import { pythonExecutor } from '../tools/pythonExecutor';

export const chartAgent = ai.definePrompt({
  model: 'googleai/gemini-1.5-pro',
  name: "chartAgent",
  description: "Creates stock price charts...",
  tools: [getHistoricalData, pythonExecutor],
  // ...
});

Has anyone done something similar or have examples to share? Any pitfalls? Would love your thoughts!

export const pythonExecutor = ai.defineTool(
  {
    name: "pythonExecutor",
    description: "Executes arbitrary Python for data transformation",
    inputSchema: z.object({ code: z.string() }),
    outputSchema: z.object({ result: z.string() }),
  },
  async ({ code }) => {
    // Example child_process approach
    return new Promise((resolve, reject) => {
      const proc = spawn('python', ['-c', code]);
      let out = '', err = '';
      proc.stdout.on('data', (d) => (out += d));
      proc.stderr.on('data', (d) => (err += d));
      proc.on('close', (code) =>
        code === 0 ? resolve({ result: out.trim() }) : reject(err)
      );
    });
  }
);
Was this page helpful?