import OpenAI from "openai";
import { DockerIsol8 } from "isol8";
const openai = new OpenAI();
const isol8 = new DockerIsol8({ mode: "ephemeral", network: "none" });
await isol8.start();
const tools: OpenAI.ChatCompletionTool[] = [
{
type: "function",
function: {
name: "execute_code",
description: "Execute Python code in a secure sandbox and return the output",
parameters: {
type: "object",
properties: {
code: { type: "string", description: "Python code to execute" },
},
required: ["code"],
},
},
},
];
async function chat(userMessage: string) {
const messages: OpenAI.ChatCompletionMessageParam[] = [
{ role: "system", content: "You can execute Python code to answer questions. Use the execute_code tool." },
{ role: "user", content: userMessage },
];
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages,
tools,
});
const toolCall = response.choices[0].message.tool_calls?.[0];
if (toolCall?.function.name === "execute_code") {
const { code } = JSON.parse(toolCall.function.arguments);
const result = await isol8.execute({ code, runtime: "python" });
// Feed result back to the model
messages.push(response.choices[0].message);
messages.push({
role: "tool",
tool_call_id: toolCall.id,
content: JSON.stringify({
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
}),
});
const finalResponse = await openai.chat.completions.create({
model: "gpt-4o",
messages,
});
return finalResponse.choices[0].message.content;
}
return response.choices[0].message.content;
}
// Usage
const answer = await chat("What is the 50th Fibonacci number?");
console.log(answer);