Skip to main content
Khoj can generate and execute Python code in a secure sandbox. Perfect for calculations, data analysis, generating reports, or any task requiring computational precision.

Why Code Execution?

Large language models struggle with:
  • Complex math and calculations
  • Data processing and analysis
  • Generating charts and visualizations
  • Precise quantitative tasks
Code execution solves this by letting Khoj write and run actual Python code for accurate results.

How It Works

1

Task Detection

Khoj identifies when code would be helpful:
  • Mathematical calculations
  • Data manipulation
  • File processing
  • Chart generation
2

Code Generation

Khoj writes Python code to solve the task
3

Secure Execution

Code runs in an isolated sandbox environment:
  • No access to your files or network
  • Limited execution time
  • Controlled resource usage
4

Results Integration

Output is captured and presented in the chat:
  • Printed values
  • Generated plots/charts
  • Error messages if code fails
Khoj automatically decides when to use code execution. You can also explicitly request it with the /code command.

Using Code Execution

Simply ask for computational tasks:
Calculate compound interest on $10,000 at 5% annually for 10 years
Generate a bar chart comparing sales data: 
Q1: 45000, Q2: 52000, Q3: 48000, Q4: 61000
What's the standard deviation of these numbers: 12, 15, 18, 22, 25, 29
Khoj detects the need for code and runs it automatically.

Example Use Cases

Complex Calculations:
Calculate the area under the curve y = x^2 from x=0 to x=5 using numerical integration
Statistical Analysis:
/code Find the mean, median, mode, and range of: 23, 45, 12, 67, 45, 89, 34, 45, 78
Financial Math:
Compare monthly payment for a $300,000 mortgage at 4% vs 5% interest over 30 years
Processing Lists:
/code I have these test scores: [78, 85, 92, 88, 76, 95, 89]. 
Calculate average, highest, lowest, and how many are above 85.
Trend Analysis:
Analyze this monthly revenue trend and tell me if it's growing: 
Jan: 50k, Feb: 53k, Mar: 49k, Apr: 55k, May: 58k, Jun: 62k
Data Transformation:
Convert these temperatures from Fahrenheit to Celsius: 72, 85, 90, 68, 75
Charts:
Create a pie chart of my time allocation: Work 40%, Sleep 32%, 
Leisure 18%, Exercise 10%
Graphs:
/code Plot the function y = sin(x) * e^(-x/10) for x from 0 to 20
Comparisons:
Make a bar chart comparing populations: Tokyo 37M, Delhi 31M, 
Shanghai 27M, São Paulo 22M, Mexico City 22M
Analysis:
/code Count word frequency in this text: [paste paragraph]
Manipulation:
Generate all possible 3-letter combinations of 'ABC'
Parsing:
Extract all email addresses from this text: [paste content]
Probability:
Simulate rolling two dice 10,000 times and show the distribution of sums
Monte Carlo:
/code Estimate the value of pi using Monte Carlo simulation with 100,000 random points
Modeling:
Simulate population growth starting with 100, growing at 5% per year for 20 years

What You’ll See

When Khoj runs code, you get:
The actual Python code that was executed:
```python
# Calculate compound interest
principal = 10000
rate = 0.05
years = 10

amount = principal * (1 + rate) ** years
interest = amount - principal

print(f"Final amount: ${amount:.2f}")
print(f"Interest earned: ${interest:.2f}")
```

Supported Python Libraries

Standard Library:
  • math, statistics, random
  • datetime, time
  • json, csv
  • re (regex)
  • collections, itertools
Data & Math:
  • numpy
  • pandas (basic operations)
  • scipy
Visualization:
  • matplotlib
  • seaborn (if available)
If you need a specific library, ask! Khoj will attempt to use it or suggest alternatives.

Limitations

Current constraints:
Code cannot read or write to your actual files.Workaround: Copy-paste data into the chat for processing.
Cannot make HTTP requests or access external APIs.Workaround: Use /online search first, then process data with /code.
Long-running code will timeout (typically 30-60 seconds).Workaround: Optimize algorithms or reduce problem size.
Large datasets may exceed available memory.Workaround: Work with smaller samples or summaries.
Best for straightforward scripts, not complex applications.Limitation: Multi-file projects or complex architectures not supported.

Self-Hosting Setup

Configure code execution for your self-hosted instance:
1

Using Docker Compose

Automatic setup with the standard docker-compose.yml:
docker-compose up
Terrarium sandbox starts automatically!
2

Manual Docker Setup

If not using docker-compose:
docker pull ghcr.io/khoj-ai/terrarium:latest
docker run -d -p 8080:8080 ghcr.io/khoj-ai/terrarium:latest
3

Verify Installation

Test the sandbox:
curl -X POST -H "Content-Type: application/json" \
  --url http://localhost:8080 \
  --data-raw '{"code": "1 + 1"}' \
  --no-buffer
Should return: 2
Benefits:
  • Free and open source
  • Runs locally
  • No API keys needed
  • Lightweight
Limitations:
  • Limited Python package set
  • Basic sandbox features
Terrarium GitHub →

Option 2: E2B Sandbox

1

Get API Key

Sign up at e2b.dev and generate an API key from dashboard
2

Set Environment Variable

export E2B_API_KEY=your_api_key_here
Or in docker-compose.yml:
environment:
  - E2B_API_KEY=your_api_key_here
3

Restart Khoj

Restart your Khoj server to switch to E2B
Benefits:
  • Wide Python package support
  • More powerful sandbox
  • pip install capability
  • Better for complex code
Cost:
Start with Terrarium (free). Upgrade to E2B if you need more packages or advanced features.

Best Practices

Be Specific

Clearly describe what you want calculated or analyzed

Provide Data

Include actual numbers or datasets in your message

Verify Results

Review the code to understand how the answer was reached

Iterate

Ask follow-up questions to refine or expand analysis

Advanced Examples

I have this sales data:
Week 1: 234 units
Week 2: 287 units
Week 3: 256 units
Week 4: 312 units
Week 5: 298 units
Week 6: 334 units

/code Calculate:
1. Average weekly sales
2. Growth rate (first week to last)
3. Standard deviation
4. Predict next week using linear trend
5. Create a line chart showing the trend

Combining with Other Features

Troubleshooting

Self-hosted:
  • Verify Terrarium is running: docker ps | grep terrarium
  • Check Terrarium logs: docker logs <container-id>
  • Test sandbox directly (see verification step above)
  • Ensure E2B_API_KEY is valid (if using E2B)
  • Restart Khoj server
Cloud:
  • Feature should work automatically
  • Try explicit /code command
  • Report if persistent issue
Common issues:
  • Library not available in sandbox
  • Syntax error in generated code
  • Timeout due to complexity
Solutions:
  • Simplify the request
  • Ask Khoj to “try again with different approach”
  • Request specific library usage
  • Check error message and iterate
Terrarium:
  • Limited to pre-installed packages
  • Ask Khoj to use alternatives
E2B:
  • Most packages available
  • Ask Khoj to pip install if needed
Workaround:
  • Use built-in libraries
  • Implement functionality manually
Causes:
  • Complex calculations
  • Large datasets
  • Inefficient algorithms
Solutions:
  • Reduce problem size
  • Ask for optimized approach
  • Use sampling for large data

Security & Safety

Code execution is safe:
  • Runs in isolated sandbox
  • No access to your files or network
  • Cannot install system packages
  • Execution time limited
  • Memory constrained
  • Separate from Khoj server
While sandboxed, always review code before accepting results for critical applications.

Next Steps

Online Search + Code

Combine web research with data analysis

Automate Analysis

Schedule recurring code execution tasks

Chat Commands

Learn more slash commands and features

Build docs developers (and LLMs) love