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

JSON_FENCE =

Returns Opening fenced JSON marker.

Returns:

  • (String) —

    Opening fenced JSON marker

"```json".b.freeze
CLOSING_FENCE =

Returns Closing fenced JSON marker.

Returns:

  • (String) —

    Closing fenced JSON marker

"```".b.freeze
WHITESPACE_BYTES =

Returns JSON whitespace byte values.

Returns:

  • (Array<Integer>) —

    JSON whitespace byte values

[9, 10, 11, 12, 13, 32].freeze

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.



22
23
24
# File 'lib/prescient/agent/parser.rb', line 22

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



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

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



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/prescient/agent/parser.rb', line 29

def parse(text)
  action_json = extract_action_json(text.to_s)
  return nil unless action_json
  raise MalformedActionError, "agent action exceeds configured size limit" if action_json.bytesize > @max_bytes

  payload = JSON.parse(action_json)
  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