Skip to main content
Code Runner enables Zark to write and execute Python code in real-time — precise calculations, statistical analysis, financial modeling, scientific computing, and data processing that would be impossible through text alone.

Quick Start

import requests

response = requests.post(
    "https://api.zarkai.xyz/v1/chat",
    headers={
        "x-api-key": "your_api_key",
        "Content-Type": "application/json",
    },
    json={
        "messages": [
            {"role": "user", "content": "Calculate compound interest for $10,000 at 5% annually for 10 years"}
        ],
        "workspace_id": "wks-xxxxx",
        "tools": ["code_runner"],
        "tool_choice": "auto",
    },
)

data = response.json()
print(data["response"])

When to Use Code Runner

Code Runner is the right tool when you need exact answers — not approximations:
CategoryExamples
Financial modelingCompound interest, Sharpe ratio, option pricing, portfolio optimization
Statistical analysist-tests, regression, correlation, probability distributions
Scientific computingDifferential equations, simulations, numerical methods
Data processingAggregations, transformations, and computations on datasets
Precise arithmeticAny calculation where rounding or estimation isn’t acceptable

Iterative Execution

Code Runner doesn’t just run code once — it runs iteratively. The model writes code, executes it, inspects the output, and can run additional computations to refine the analysis:
{
  "messages": [
    {"role": "user", "content": "Run a Monte Carlo simulation with 10,000 trials for a portfolio with 60% stocks and 40% bonds. Calculate the 5th percentile VaR."}
  ],
  "workspace_id": "wks-xxxxx",
  "tools": ["code_runner"],
  "tool_choice": "auto"
}
Zark may execute multiple code blocks — building the simulation, running it, computing statistics, and formatting the output — all in a single request.

Working with Uploaded Data

Code Runner can analyze data from your uploaded files or from other tools in the same request:
{
  "messages": [
    {"role": "user", "content": "Run a t-test comparing Q3 and Q2 revenue from my sales data"}
  ],
  "workspace_id": "wks-xxxxx",
  "tools": ["code_runner", "database"],
  "file_ids": ["file-sales123"],
  "tool_choice": "auto"
}
Zark queries the data first, then passes the results to Code Runner for the statistical test.

Saving Results

Code Runner can persist its outputs as tables and files in your Space. When you ask to “simulate and save” or “compute and create a table,” Code Runner handles both the computation and the saving in a single step:
{
  "messages": [
    {"role": "user", "content": "Simulate 1000 stock price paths using geometric Brownian motion and save the results as a table"}
  ],
  "workspace_id": "wks-xxxxx",
  "tools": ["code_runner"],
  "tool_choice": "auto"
}

Streaming

Python
import requests
import json

response = requests.post(
    "https://api.zarkai.xyz/v1/chat",
    headers={"x-api-key": "your_api_key", "Content-Type": "application/json"},
    json={
        "messages": [{"role": "user", "content": "Perform linear regression and predict next quarter"}],
        "workspace_id": "wks-xxxxx",
        "tools": ["code_runner"],
        "file_ids": ["file-data789"],
        "stream": True,
    },
    stream=True,
)

for line in response.iter_lines():
    if line:
        event = json.loads(line.decode("utf-8").removeprefix("data: "))
        if event["type"] == "ai_chunk":
            print(event["content"], end="", flush=True)
        elif event["type"] == "ai_complete":
            print(f"\n\nDone.")

Streaming Events

EventDescription
ai_chunkIncremental text with computation results and analysis
ai_completeFinal response with complete results

When to Use Code Runner vs Other Tools

Want to…Use
Query or filter existing dataDatabase Queries
Modify table structure (add/rename columns, merge)Table Workshop
Run precise calculations, statistics, or simulationsCode Runner
Build a script or app to keep and reuseArtifact Creator
The key distinction: Code Runner executes code and returns results. Artifact Creator creates code as a saved file.

Best Practices

Be specific about what you want calculated:
# Good: specific and clear
"Calculate the Sharpe ratio for returns [0.12, 0.08, -0.03, 0.15] with risk-free rate 0.02"

# Avoid: vague
"Analyze this data"
Provide data and constraints:
# Good: includes data
"Perform a t-test comparing Group A [23, 25, 28, 30] and Group B [20, 22, 24, 26] at 95% confidence"

Examples

Calculate the compound annual growth rate from 2020 to 2025
Run a Monte Carlo simulation with 10,000 trials for this portfolio
Perform linear regression on this dataset and predict next quarter
Calculate the Sharpe ratio, Sortino ratio, and max drawdown
Solve this differential equation: dy/dx = x² + y, with y(0) = 1