Class: OpenSandbox::Execd::CodeInterpreter

Inherits:
Object
  • Object
show all
Defined in:
lib/open_sandbox/execd/code_interpreter.rb

Defined Under Namespace

Classes: CodeResult, Context

Instance Method Summary collapse

Constructor Details

#initialize(execd) ⇒ CodeInterpreter

Returns a new instance of CodeInterpreter.



11
12
13
# File 'lib/open_sandbox/execd/code_interpreter.rb', line 11

def initialize(execd)
  @execd = execd
end

Instance Method Details

#create_context(language: "python") ⇒ Object

Create a new code execution context.



16
17
18
19
20
# File 'lib/open_sandbox/execd/code_interpreter.rb', line 16

def create_context(language: "python")
  response = @execd.proxy(method: :post, path: "/code/context", body: { language: language })
  data = JSON.parse(response.body)
  Context.new(id: data["contextId"] || data["id"], language: language)
end

#delete_context(context_id) ⇒ Object

Delete a context.



33
34
35
# File 'lib/open_sandbox/execd/code_interpreter.rb', line 33

def delete_context(context_id)
  @execd.proxy(method: :delete, path: "/code/contexts/#{context_id}")
end

#list_contexts(language: nil) ⇒ Object

List active contexts.



23
24
25
26
27
28
29
30
# File 'lib/open_sandbox/execd/code_interpreter.rb', line 23

def list_contexts(language: nil)
  query_path = "/code/contexts"
  query_path += "?language=#{language}" if language
  response = @execd.proxy(method: :get, path: query_path)
  data = JSON.parse(response.body)
  contexts = data.is_a?(Array) ? data : (data["contexts"] || [])
  contexts.map { |c| Context.new(id: c["id"], language: c["language"]) }
end

#run(code, context_id: nil, language: "python", &block) ⇒ Object

Execute code in a context. Returns parsed result from streaming JSON/SSE response. If a block is given, yields each parsed event as it arrives.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/open_sandbox/execd/code_interpreter.rb', line 39

def run(code, context_id: nil, language: "python", &block)
  context = { language: language }
  context[:id] = context_id if context_id
  body = { code: code, context: context }

  if block_given?
    parse_streaming_response(block) do |chunk_handler|
      @execd.proxy_stream(method: :post, path: "/code", body: body, &chunk_handler)
    end
  else
    response = @execd.proxy(method: :post, path: "/code", body: body)
    parse_sse_code_response(response.body)
  end
end