Class: Prescient::Agent::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/prescient/agent/parser.rb

Overview

Extracts and validates one tool action from provider text.

Constant Summary collapse

ACTION_PATTERN =

Returns Fenced JSON action matcher.

Returns:

  • (Regexp)

    Fenced JSON action matcher

/```json\s*(\{.*?\})\s*```/m

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_bytes: Configuration::DEFAULT_MAX_ACTION_BYTES) ⇒ Parser

Returns a new instance of Parser.



18
19
20
# File 'lib/prescient/agent/parser.rb', line 18

def initialize(max_bytes: Configuration::DEFAULT_MAX_ACTION_BYTES)
  @max_bytes = max_bytes
end

Class Method Details

.parse(text, max_bytes: Configuration::DEFAULT_MAX_ACTION_BYTES) ⇒ Hash?

Parse one optional action from provider output.

Parameters:

  • text (String)

    Provider response text

  • max_bytes (Integer) (defaults to: Configuration::DEFAULT_MAX_ACTION_BYTES)

    Maximum action size

Returns:

  • (Hash, nil)

    Parsed action or nil for a final response



14
15
16
# File 'lib/prescient/agent/parser.rb', line 14

def self.parse(text, max_bytes: Configuration::DEFAULT_MAX_ACTION_BYTES)
  new(max_bytes:).parse(text)
end

Instance Method Details

#parse(text) ⇒ Hash?

Parse one optional action from provider output.

Parameters:

  • text (String)

    Provider response text

Returns:

  • (Hash, nil)

    Parsed action or nil for a final response



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/prescient/agent/parser.rb', line 25

def parse(text)
  match = text.to_s.match(ACTION_PATTERN)
  return nil unless match
  raise MalformedActionError, "agent action exceeds configured size limit" if match[1].bytesize > @max_bytes

  payload = JSON.parse(match[1])
  validate_payload(payload)
  { name: payload.fetch("action").to_sym, arguments: payload.fetch("args") }
rescue JSON::ParserError => e
  raise MalformedActionError, "agent action contains invalid JSON: #{e.message}"
end