import Anthropic from "@anthropic-ai/sdk";
import GboxSDK from "gbox-sdk";
import * as dotenv from "dotenv";
dotenv.config();
// Initialize clients
const anthropicClient = new Anthropic({
apiKey: process.env["ANTHROPIC_API_KEY"],
});
const gboxSDK = new GboxSDK({
apiKey: process.env["GBOX_API_KEY"],
});
// Extract Python code blocks
function extractPythonCode(text: string): string[] {
const regex = /```python\n([\s\S]*?)\n```/g;
const codeBlocks: string[] = [];
let match;
while ((match = regex.exec(text)) !== null) {
codeBlocks.push(match[1].trim());
}
return codeBlocks;
}
async function main() {
try {
// 1. Generate Python code using Anthropic Claude
const response = await anthropicClient.messages.create({
model: "claude-3-7-sonnet-20250219",
max_tokens: 1000,
temperature: 0.7,
system:
"Generate Python code to solve problems. Always wrap code in ```python blocks.",
messages: [
{
role: "user",
content: "Calculate the first 10 Fibonacci numbers",
},
],
});
const aiResponse =
response.content[0].type === "text" ? response.content[0].text : "";
console.log("\nAnthropic Claude Response:");
console.log(aiResponse);
// 2. Extract and execute Python code
const codeBlocks = extractPythonCode(aiResponse);
if (codeBlocks.length === 0) {
console.log("No executable code found");
return;
}
// 3. Execute code in GBOX
const box = await gboxSDK.create({ type: "linux" });
try {
for (const code of codeBlocks) {
console.log("\nExecuting code:");
console.log(code);
console.log("---");
const result = await box.runCode(code);
console.log("Execution result:");
console.log(result.stdout || result.stderr || "No output");
}
} finally {
await box.terminate();
}
} catch (error) {
console.error("Error:", error);
}
}
main();