or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

audio.mdbatch.mdchat-completions.mdcode-interpreter.mdcompletions.mdembeddings.mdendpoints.mdevaluation.mdfiles.mdfine-tuning.mdimages.mdindex.mdmodels.mdrerank.md

code-interpreter.mddocs/

0

# Code Interpreter

1

2

Interactive code execution environment for running Python scripts with file upload support and session management. Enables dynamic code execution with persistent sessions, file handling, and comprehensive output capture including stdout, stderr, and visual displays.

3

4

## Capabilities

5

6

### Code Execution

7

8

Execute Python code snippets with optional file inputs and session persistence for interactive workflows.

9

10

```python { .api }

11

def run(

12

code: str,

13

language: Literal["python"],

14

session_id: Optional[str] = None,

15

files: Optional[List[Dict[str, Any]]] = None

16

) -> ExecuteResponse:

17

"""

18

Execute a code snippet, optionally with files.

19

20

Args:

21

code: Code snippet to execute

22

language: Programming language ("python" only currently supported)

23

session_id: Identifier of current session for follow-up calls

24

files: Files to upload before executing code

25

26

Returns:

27

ExecuteResponse: Object containing execution results and outputs

28

29

Raises:

30

ValidationError: If files don't conform to required structure

31

"""

32

```

33

34

**Basic Usage Example:**

35

36

```python

37

from together import Together

38

39

client = Together()

40

41

# Execute simple Python code

42

response = client.code_interpreter.run(

43

code="print('Hello, World!')\nresult = 42\nprint(f'The answer is {result}')",

44

language="python"

45

)

46

47

# Access outputs

48

for output in response.data.outputs:

49

if output.type == "stdout":

50

print("Output:", output.data)

51

52

print(f"Session ID: {response.data.session_id}")

53

```

54

55

**Session Persistence Example:**

56

57

```python

58

from together import Together

59

60

client = Together()

61

62

# First execution - creates a session

63

response1 = client.code_interpreter.run(

64

code="x = 10\ny = 20\nprint(f'x = {x}, y = {y}')",

65

language="python"

66

)

67

68

session_id = response1.data.session_id

69

70

# Second execution - reuses the session with variables preserved

71

response2 = client.code_interpreter.run(

72

code="z = x + y\nprint(f'z = x + y = {z}')",

73

language="python",

74

session_id=session_id

75

)

76

77

# Variables from previous execution are still available

78

for output in response2.data.outputs:

79

if output.type == "stdout":

80

print("Persistent session output:", output.data)

81

```

82

83

**File Upload Example:**

84

85

```python

86

import base64

87

from together import Together

88

89

client = Together()

90

91

# Prepare file inputs

92

files = [

93

{

94

"name": "data.txt",

95

"encoding": "string",

96

"content": "apple,banana,cherry\ndog,elephant,fox"

97

},

98

{

99

"name": "config.json",

100

"encoding": "string",

101

"content": '{"delimiter": ",", "header": false}'

102

}

103

]

104

105

# Execute code with file inputs

106

response = client.code_interpreter.run(

107

code="""

108

import json

109

110

# Read the data file

111

with open('data.txt', 'r') as f:

112

data = f.read()

113

114

# Read the config file

115

with open('config.json', 'r') as f:

116

config = json.load(f)

117

118

# Process the data

119

lines = data.strip().split('\\n')

120

delimiter = config['delimiter']

121

122

for line in lines:

123

items = line.split(delimiter)

124

print(f"Items: {items}")

125

126

print(f"Total lines processed: {len(lines)}")

127

""",

128

language="python",

129

files=files

130

)

131

132

# Process outputs

133

for output in response.data.outputs:

134

if output.type == "stdout":

135

print("File processing output:", output.data)

136

elif output.type == "stderr":

137

print("Error:", output.data)

138

```

139

140

**Data Analysis Example:**

141

142

```python

143

from together import Together

144

145

client = Together()

146

147

# Upload CSV data and analyze it

148

csv_data = """date,temperature,humidity

149

2024-01-01,22.5,65

150

2024-01-02,24.1,62

151

2024-01-03,21.8,68

152

2024-01-04,23.9,64

153

2024-01-05,25.2,61"""

154

155

files = [

156

{

157

"name": "weather.csv",

158

"encoding": "string",

159

"content": csv_data

160

}

161

]

162

163

response = client.code_interpreter.run(

164

code="""

165

import csv

166

import statistics

167

168

# Read and parse CSV data

169

data = []

170

with open('weather.csv', 'r') as f:

171

reader = csv.DictReader(f)

172

for row in reader:

173

data.append({

174

'date': row['date'],

175

'temperature': float(row['temperature']),

176

'humidity': int(row['humidity'])

177

})

178

179

# Calculate statistics

180

temps = [d['temperature'] for d in data]

181

humidities = [d['humidity'] for d in data]

182

183

print(f"Temperature Statistics:")

184

print(f" Average: {statistics.mean(temps):.1f}°C")

185

print(f" Min: {min(temps)}°C")

186

print(f" Max: {max(temps)}°C")

187

188

print(f"\\nHumidity Statistics:")

189

print(f" Average: {statistics.mean(humidities):.1f}%")

190

print(f" Min: {min(humidities)}%")

191

print(f" Max: {max(humidities)}%")

192

193

# Find hottest day

194

hottest = max(data, key=lambda x: x['temperature'])

195

print(f"\\nHottest day: {hottest['date']} at {hottest['temperature']}°C")

196

""",

197

language="python",

198

files=files

199

)

200

201

# Display results

202

for output in response.data.outputs:

203

if output.type == "stdout":

204

print("Analysis results:")

205

print(output.data)

206

```

207

208

**Binary File Handling Example:**

209

210

```python

211

import base64

212

from together import Together

213

214

client = Together()

215

216

# Create a simple binary file (example: small image data)

217

# In practice, you'd read this from an actual file

218

binary_content = b"\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x01"

219

base64_content = base64.b64encode(binary_content).decode('utf-8')

220

221

files = [

222

{

223

"name": "small_image.png",

224

"encoding": "base64",

225

"content": base64_content

226

}

227

]

228

229

response = client.code_interpreter.run(

230

code="""

231

import os

232

233

# Check file exists and get info

234

if os.path.exists('small_image.png'):

235

size = os.path.getsize('small_image.png')

236

print(f"File 'small_image.png' exists with size: {size} bytes")

237

238

# Read binary data

239

with open('small_image.png', 'rb') as f:

240

data = f.read()

241

242

print(f"First 10 bytes: {data[:10]}")

243

else:

244

print("File not found")

245

""",

246

language="python",

247

files=files

248

)

249

250

for output in response.data.outputs:

251

if output.type == "stdout":

252

print("Binary file output:", output.data)

253

```

254

255

## Output Types

256

257

The code interpreter captures various types of execution outputs:

258

259

**Output Type Examples:**

260

261

```python

262

from together import Together

263

264

client = Together()

265

266

response = client.code_interpreter.run(

267

code="""

268

# stdout output

269

print("This goes to stdout")

270

271

# stderr output

272

import sys

273

print("This goes to stderr", file=sys.stderr)

274

275

# Return value

276

42

277

278

# Error handling

279

try:

280

1 / 0

281

except ZeroDivisionError as e:

282

print(f"Caught error: {e}")

283

""",

284

language="python"

285

)

286

287

for output in response.data.outputs:

288

print(f"Type: {output.type}")

289

print(f"Data: {output.data}")

290

print("---")

291

```

292

293

## Types

294

295

### Core Code Interpreter Types

296

297

```python { .api }

298

class FileInput:

299

name: str

300

encoding: Literal["string", "base64"]

301

content: str

302

303

class InterpreterOutput:

304

type: Literal["stdout", "stderr", "error", "display_data", "execute_result"]

305

data: Union[str, Dict[str, Any]]

306

307

class ExecuteResponseData:

308

outputs: List[InterpreterOutput]

309

errors: Optional[str]

310

session_id: str

311

status: str

312

313

class ExecuteResponse:

314

data: ExecuteResponseData

315

```

316

317

## Error Handling

318

319

Handle validation errors and execution failures gracefully:

320

321

```python

322

from together import Together

323

from together.error import APIError

324

325

client = Together()

326

327

# Invalid file input example

328

try:

329

response = client.code_interpreter.run(

330

code="print('Hello')",

331

language="python",

332

files=[

333

{

334

"name": "test.txt",

335

# Missing required 'encoding' field

336

"content": "test content"

337

}

338

]

339

)

340

except ValueError as e:

341

print(f"File validation error: {e}")

342

343

# Handle execution errors

344

response = client.code_interpreter.run(

345

code="raise ValueError('This is a test error')",

346

language="python"

347

)

348

349

if response.data.errors:

350

print(f"Execution error: {response.data.errors}")

351

352

for output in response.data.outputs:

353

if output.type == "error":

354

print(f"Error output: {output.data}")

355

```

356

357

## Session Management

358

359

Code interpreter sessions maintain state across multiple executions:

360

361

```python

362

from together import Together

363

364

client = Together()

365

366

# Start a session with imports and setup

367

setup_response = client.code_interpreter.run(

368

code="""

369

import math

370

import random

371

372

# Setup some variables

373

pi_value = math.pi

374

random.seed(42)

375

setup_complete = True

376

377

print("Session initialized")

378

""",

379

language="python"

380

)

381

382

session_id = setup_response.data.session_id

383

384

# Use the session for calculations

385

calc_response = client.code_interpreter.run(

386

code="""

387

# Variables from previous execution are available

388

print(f"Pi value: {pi_value}")

389

print(f"Setup complete: {setup_complete}")

390

391

# Generate some random numbers with the seeded generator

392

numbers = [random.randint(1, 100) for _ in range(5)]

393

print(f"Random numbers: {numbers}")

394

395

# Use math functions

396

area = pi_value * (5 ** 2)

397

print(f"Area of circle with radius 5: {area:.2f}")

398

""",

399

language="python",

400

session_id=session_id

401

)

402

403

# Continue the session

404

final_response = client.code_interpreter.run(

405

code="""

406

# Previous variables and state are still available

407

print(f"Previously generated numbers: {numbers}")

408

print(f"Sum of numbers: {sum(numbers)}")

409

""",

410

language="python",

411

session_id=session_id

412

)

413

```

414

415

## Advanced Usage Patterns

416

417

**Interactive Data Science Workflow:**

418

419

```python

420

from together import Together

421

422

client = Together()

423

424

# Step 1: Data preparation

425

response1 = client.code_interpreter.run(

426

code="""

427

import numpy as np

428

import statistics

429

430

# Generate sample data

431

np.random.seed(42)

432

data = np.random.normal(100, 15, 1000)

433

print(f"Generated {len(data)} data points")

434

print(f"Mean: {np.mean(data):.2f}")

435

print(f"Std: {np.std(data):.2f}")

436

""",

437

language="python"

438

)

439

440

session_id = response1.data.session_id

441

442

# Step 2: Data analysis

443

response2 = client.code_interpreter.run(

444

code="""

445

# Analyze the data (data variable from previous step)

446

percentiles = [25, 50, 75, 90, 95, 99]

447

for p in percentiles:

448

value = np.percentile(data, p)

449

print(f"{p}th percentile: {value:.2f}")

450

451

# Find outliers (values beyond 2 standard deviations)

452

mean = np.mean(data)

453

std = np.std(data)

454

outliers = data[(data < mean - 2*std) | (data > mean + 2*std)]

455

print(f"\\nFound {len(outliers)} outliers")

456

""",

457

language="python",

458

session_id=session_id

459

)

460

461

# Step 3: Generate report

462

response3 = client.code_interpreter.run(

463

code="""

464

# Generate summary report

465

report = f'''

466

Data Analysis Report

467

===================

468

Sample size: {len(data)}

469

Mean: {np.mean(data):.2f}

470

Median: {np.median(data):.2f}

471

Standard deviation: {np.std(data):.2f}

472

Min value: {np.min(data):.2f}

473

Max value: {np.max(data):.2f}

474

Outliers detected: {len(outliers)}

475

'''

476

477

print(report)

478

479

# Save report to file

480

with open('analysis_report.txt', 'w') as f:

481

f.write(report)

482

483

print("Report saved to analysis_report.txt")

484

""",

485

language="python",

486

session_id=session_id

487

)

488

```