Skip to content

Instantly share code, notes, and snippets.

@thekid
Last active April 12, 2026 16:58
Show Gist options
  • Select an option

  • Save thekid/ba3fd77a4348f81329b322a4c8a06d27 to your computer and use it in GitHub Desktop.

Select an option

Save thekid/ba3fd77a4348f81329b322a4c8a06d27 to your computer and use it in GitHub Desktop.
xp-forge/aws: Use code interpreter
<?php
use com\amazon\aws\{CredentialProvider, ServiceEndpoint};
use lang\{Closeable, Value};
use util\cmd\Console;
use util\{Comparison, Objects};
use util\log\Logging;
/** @see https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/code-interpreter-resource-session-management.html */
class CodeInterpreter {
public function __construct(private ServiceEndpoint $api, private string $identifier) { }
public function start(string $name, string $description= 'Session', int $timeout= 60): Session {
return new Session($this->api, $this->api
->resource('/code-interpreters/{0}/sessions/start', [$this->identifier])
->transmit(method: 'PUT', payload: [
'name' => $name,
'description' => $description,
'sessionTimeoutSeconds' => $timeout,
])
->value()
);
}
}
class Session implements Closeable, Value {
use Comparison;
private $id= 1;
public function __construct(private ServiceEndpoint $api, private $session) { }
public function invoke(string $tool, array $arguments) {
return $this->api
->resource('/code-interpreters/{codeInterpreterIdentifier}/tools/invoke', $this->session)
->with(['x-amzn-code-interpreter-session-id' => $this->session['sessionId']])
->transmit(['id' => (string)$this->id++, 'name' => $tool, 'arguments' => $arguments])
->events()
;
}
public function close(): void {
if (null === $this->session) return;
$this->api
->resource('/code-interpreters/{codeInterpreterIdentifier}/sessions/stop?sessionId={sessionId}', $this->session)
->transmit(method: 'PUT', payload: (object)[])
;
$this->session= null;
}
public function toString() {
return nameof($this).'@'.Objects::stringOf($this->session);
}
/** Ensures session is closed */
public function __destruct() {
$this->close();
}
}
$api= (new ServiceEndpoint('bedrock-agentcore', CredentialProvider::default()))->in('eu-central-1');
// $api->setTrace(Logging::all()->toConsole());
$interpreter= new CodeInterpreter($api, 'aws.codeinterpreter.v1');
$session= $interpreter->start('code-session-6100', 'Test session');
Console::writeLine($session);
$files= [];
if (is_file($argv[2])) {
$offset= 2;
$code= 'import '.preg_replace('/\.py$/', '', $argv[2]);
} else {
$offset= 3;
$code= $argv[2];
}
while ($offset < $argc) {
$files[]= ['path' => $argv[$offset], 'text' => file_get_contents($argv[$offset])];
$offset++;
}
$files && $session->invoke('writeFiles', ['content' => $files]);
// Finally, run code
$events= $session->invoke('executeCode', ['language' => $argv[1], 'code' => $code]);
foreach ($events as $event) {
Console::writeLine($event->header(':event-type'), ': ', $event->value());
}
$session->close();
@thekid
Copy link
Copy Markdown
Author

thekid commented Apr 10, 2026

Example

test.py:

from pathlib import Path

file_path = 'test.txt'
contents = Path(file_path).read_text()
print(f'{file_path} contents:')
print('=' * 72)
print(contents)

test.txt:

This is test file

It's not very long

Run:

$ xp codeinterpreter.script.php python test.py test.txt
Session@[
  codeInterpreterIdentifier => "aws.codeinterpreter.v1"
  createdAt => "2026-04-10T19:08:37.328021016Z"
  sessionId => "01KNWCQN3QZBSYPY1CR60WQQJ1"
]
result: [
  content => [[
    text => "test.txt contents:
========================================================================
This is test file

It's not very long"
    type => "text"
  ]]
  isError => false
  structuredContent => [
    executionTime => 0.060420989990234
    exitCode => 0
    stderr => ""
    stdout => "test.txt contents:
========================================================================
This is test file

It's not very long"
  ]
}

See also

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment