# Code Sandboxing and Execution

URL: https://interfaze.ai/docs/compute/code-sandboxing

Run code in sandboxes for Python and TypeScript in isolated secure environments with sub-second spin up times.

- Python & TypeScript support
- \<100ms spin up times
- Isolated environments close to the GPUs
- Massive parallelism with thousands of concurrent executions

## Basic example

**Interfaze SDK · typescript**

```typescript
import { responseFormat } from "interfaze";
import { z } from "zod";

const FactorialSchema = z.object({
	fractional: z.number(),
});

const response = await interfaze.chat.completions.create({
	messages: [
		{
			role: "user",
			content: "What is the factorial of 5?",
		},
	],
	response_format: responseFormat(z.toJSONSchema(FactorialSchema), "factorial_schema"),
});

console.log(JSON.parse(response.choices[0]?.message.content ?? "{}"));

console.log("Sandbox Results:", response.precontext?.[0]?.result);
```

**Vercel AI SDK · typescript**

```typescript
import { generateObject } from "ai";
import { z } from "zod";

const FactorialSchema = z.object({
	fractional: z.number(),
});

const { object, providerMetadata } = await generateObject({
	model: interfaze("interfaze-beta"),
	schema: FactorialSchema,
	messages: [
		{
			role: "user",
			content: "What is the factorial of 5?",
		},
	],
});

console.log(object);
console.log("Sandbox Results:", providerMetadata?.interfaze?.precontext?.[0]?.result);
```

**LangChain SDK · typescript**

```typescript
import { z } from "zod";

const FactorialSchema = z.object({
	fractional: z.number(),
});

const structuredModel = interfaze.withStructuredOutput(FactorialSchema, { includeRaw: true });

const response = await structuredModel.invoke([
	{
		role: "user",
		content: "What is the factorial of 5?",
	},
]);

console.log(response.parsed);

console.log("Sandbox Results:", response.raw.response_metadata.precontext?.[0]?.result);
```

**Interfaze SDK · python**

```python
from pydantic import BaseModel

class FactorialSchema(BaseModel):
    fractional: float

response = interfaze.chat.completions.parse(
    messages=[
        {
            "role": "user",
            "content": "What is the factorial of 5?",
        }
    ],
    response_format=FactorialSchema,
)

print(response.choices[0].message.parsed)

print("Sandbox Results:", response.precontext[0].result if response.precontext else None)
```

**LangChain SDK · python**

```python
from langchain_core.messages import HumanMessage
from pydantic import BaseModel

class FactorialSchema(BaseModel):
    fractional: float

structured_llm = interfaze.with_structured_output(FactorialSchema, include_raw=True)

response = structured_llm.invoke([
    HumanMessage(content="What is the factorial of 5?")
])

print(response["parsed"])

print("Sandbox Results:", response["raw"].response_metadata.get("precontext"))
```

**JSON output**

```json
{
  "object": {
    "fractional": 120
  },
  "response": {
    "id": "interfaze-1775193886199",
    "modelId": "interfaze-beta",
    "body": {
      "id": "interfaze-1775193886199",
      "object": "chat.completion",
      "model": "interfaze-beta",
      "usage": {
        "prompt_tokens": 2236,
        "completion_tokens": 21,
        "total_tokens": 2257
      },
      "precontext": [
        {
          "name": "code_execute",
          "result": {
            "code_script": "# Calculate factorial of 5 and print\nimport math\nprint(math.factorial(5))",
            "language": "python",
            "output": "120\n",
            "is_action_tool": true
          }
        }
      ]
    }
  },
  "finishReason": "stop",
  "usage": {
    "inputTokens": 2236,
    "outputTokens": 21,
    "totalTokens": 2257
  }
}
```

`precontext` contains the code generated and executed by the model to achieve the final response.

## Counting tasks

**Interfaze SDK · typescript**

```typescript
import { responseFormat } from "interfaze";
import { z } from "zod";

const CountingSchema = z.object({
	answer: z.number(),
});

const response = await interfaze.chat.completions.create({
	messages: [
		{
			role: "user",
			content: "How many r's are there in strawberry?",
		},
	],
	response_format: responseFormat(z.toJSONSchema(CountingSchema), "counting_schema"),
});

console.log(JSON.parse(response.choices[0]?.message.content ?? "{}"));

console.log("Sandbox Results:", response.precontext?.[0]?.result);
```

**Vercel AI SDK · typescript**

```typescript
import { generateObject } from "ai";
import { z } from "zod";

const CountingSchema = z.object({
	answer: z.number(),
});

const { object, providerMetadata } = await generateObject({
	model: interfaze("interfaze-beta"),
	schema: CountingSchema,
	messages: [
		{
			role: "user",
			content: "How many r's are there in strawberry?",
		},
	],
});

console.log(object);
console.log("Sandbox Results:", providerMetadata?.interfaze?.precontext?.[0]?.result);
```

**LangChain SDK · typescript**

```typescript
import { z } from "zod";

const CountingSchema = z.object({
	answer: z.number(),
});

const structuredModel = interfaze.withStructuredOutput(CountingSchema, { includeRaw: true });

const response = await structuredModel.invoke([
	{
		role: "user",
		content: "How many r's are there in strawberry?",
	},
]);

console.log(response.parsed);

console.log("Sandbox Results:", response.raw.response_metadata.precontext?.[0]?.result);
```

**Interfaze SDK · python**

```python
from pydantic import BaseModel

class CountingSchema(BaseModel):
    answer: int

response = interfaze.chat.completions.parse(
    messages=[
        {
            "role": "user",
            "content": "How many r's are there in strawberry?",
        }
    ],
    response_format=CountingSchema,
)

print(response.choices[0].message.parsed)

print("Sandbox Results:", response.precontext[0].result if response.precontext else None)
```

**LangChain SDK · python**

```python
from langchain_core.messages import HumanMessage
from pydantic import BaseModel

class CountingSchema(BaseModel):
    answer: int

structured_llm = interfaze.with_structured_output(CountingSchema, include_raw=True)

response = structured_llm.invoke([
    HumanMessage(content="How many r's are there in strawberry?")
])

print(response["parsed"])

print("Sandbox Results:", response["raw"].response_metadata.get("precontext"))
```

**JSON output**

```json
{
  "object": {
    "answer": 3
  },
  "response": {
    "id": "interfaze-1775195660480",
    "modelId": "interfaze-beta",
    "body": {
      "id": "interfaze-1775195660480",
      "object": "chat.completion",
      "model": "interfaze-beta",
      "usage": {
        "prompt_tokens": 2278,
        "completion_tokens": 21,
        "total_tokens": 2299
      },
      "precontext": [
        {
          "name": "code_execute",
          "result": {
            "code_script": "print('strawberry'.count('r'))",
            "language": "python",
            "output": "3\n",
            "is_action_tool": true
          }
        }
      ]
    }
  },
  "finishReason": "stop",
  "usage": {
    "inputTokens": 2278,
    "outputTokens": 21,
    "totalTokens": 2299
  }
}
```

## Graphical Code Generation

**Interfaze SDK · typescript**

```typescript
const response = await interfaze.chat.completions.create({
	messages: [
		{
			role: "user",
			content: "Create me a bouncing ball animation in python",
		},
	],
});

console.log(response.choices[0]?.message.content);

/*
Response -

import sys
import random
import pygame

def main():
    # Initialize Pygame
    pygame.init()
    WIDTH, HEIGHT = 800, 600
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Bouncing Ball")

    # Colors
    BG = (18, 18, 18)
    BALL_COLOR = (52, 152, 219)

    # Ball properties
    radius = 25
    x = WIDTH // 2
    y = HEIGHT // 2
    # Random initial velocity
    vx = random.choice([-5, -4, -3, 3, 4, 5])
    vy = random.choice([-5, -4, -3, 3, 4, 5])

    clock = pygame.time.Clock()
    FPS = 60

    running = True
    while running:
        # Event handling
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # Update position
        x += vx
        y += vy

        # Bounce on walls
        if x - radius <= 0:
            x = radius
            vx = -vx
        elif x + radius >= WIDTH:
            x = WIDTH - radius
            vx = -vx

        if y - radius <= 0:
            y = radius
            vy = -vy
        elif y + radius >= HEIGHT:
            y = HEIGHT - radius
            vy = -vy

        # Draw
        screen.fill(BG)
        pygame.draw.circle(screen, BALL_COLOR, (int(x), int(y)), radius)
        pygame.display.flip()

        # Cap the frame rate
        clock.tick(FPS)

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()
*/

console.log("Sandbox Results:", response.precontext?.[0]?.result);
```

**Vercel AI SDK · typescript**

```typescript
import { generateText } from "ai";

const { text, providerMetadata } = await generateText({
	model: interfaze("interfaze-beta"),
	prompt: "Create me a bouncing ball animation in python",
});

console.log(text);
console.log("Sandbox Results:", providerMetadata?.interfaze?.precontext?.[0]?.result);
```

**LangChain SDK · typescript**

```typescript
const response = await interfaze.invoke("Create me a bouncing ball animation in python");

console.log(response.content);

console.log("Sandbox Results:", response.response_metadata.precontext?.[0]?.result);
```

**Interfaze SDK · python**

```python
response = interfaze.chat.completions.create(
    messages=[
        {
            "role": "user",
            "content": "Create me a bouncing ball animation in python",
        }
    ],
)

print(response.choices[0].message.content)

print("Sandbox Results:", response.precontext[0].result if response.precontext else None)
```

**LangChain SDK · python**

```python
response = interfaze.invoke("Create me a bouncing ball animation in python")

print(response.content)

print("Sandbox Results:", response.response_metadata.get("precontext"))
```

<div style={{ padding: "20px 0" }}>![Code Generation Demo](https://r2public.jigsawstack.com/interfaze/examples/code_gen_gif.mp4)</div>
