Module: Mistri::TaskOutput

Defined in:
lib/mistri/task_output.rb

Overview

The text side of task mode: how a schema is asked for, how the answer parses, and how a violation is sent back for a fix. Pure functions over strings and schemas; Agent#task owns the loop that drives them.

Constant Summary collapse

PARSE_FAILED =

Distinguishable from a parsed nil: JSON "null" is a valid value.

Object.new.freeze
OUTPUT_TOO_LARGE =
Object.new.freeze
OUTPUT_TOO_COMPLEX =
Object.new.freeze

Class Method Summary collapse

Class Method Details

.errors(value, schema) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/mistri/task_output.rb', line 37

def errors(value, schema)
  return ["the answer exceeds the output byte limit"] if value.equal?(OUTPUT_TOO_LARGE)
  return ["the answer exceeds the output complexity limit"] if value.equal?(OUTPUT_TOO_COMPLEX)
  return ["the answer is not valid JSON"] if value.equal?(PARSE_FAILED)

  plan_for(schema).violations(value)
end

.fix_prompt(errors) ⇒ Object



45
46
47
48
49
# File 'lib/mistri/task_output.rb', line 45

def fix_prompt(errors)
  lines = errors.map { |error| "- #{error}" }.join("\n")
  "Your answer did not satisfy the required output schema. Problems:\n" \
    "#{lines}\nReply with ONLY the corrected JSON."
end

.parse(text) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/mistri/task_output.rb', line 23

def parse(text)
  body = text.to_s
  return OUTPUT_TOO_LARGE if body.bytesize > ToolArguments::MAX_BYTES

  body = body.strip
  body = body[/\A```(?:json)?\s*(.*?)```\z/m, 1] || body
  value, error = ToolArguments.parse_json(body)
  return OUTPUT_TOO_LARGE if error == "too_large"
  return OUTPUT_TOO_COMPLEX if %w[too_deep too_many_nodes number_too_large].include?(error)
  return PARSE_FAILED if error

  value
end

.prompt(input, schema) ⇒ Object



17
18
19
20
21
# File 'lib/mistri/task_output.rb', line 17

def prompt(input, schema)
  plan = plan_for(schema)
  "#{input}\n\nAnswer with ONLY a JSON value matching this schema:\n" \
    "#{JSON.generate(plan.schema)}"
end