Class: PromptBuilder::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/prompt_builder/response.rb

Overview

Represents a parsed API response from the Open Responses API. All fields are optional and will be nil if not present in the response.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**attributes) ⇒ Response

Create a new Response.

Parameters:

  • attributes (Hash)

    response attributes

Options Hash (**attributes):

  • :extra (Hash, nil)

    provider-specific response metadata that has no canonical Open Responses slot (e.g. Gemini grounding and citation metadata, candidate safety ratings, logprobs results)



146
147
148
149
150
151
152
# File 'lib/prompt_builder/response.rb', line 146

def initialize(**attributes)
  FIELDS.each { |f| instance_variable_set(:"@#{f}", coerce_field(f, attributes[f])) }
  @text_config = PromptBuilder.jsonify(attributes[:text_config])
  @output = attributes[:output] || []
  @usage = attributes[:usage]
  @extra = PromptBuilder.jsonify(attributes[:extra])
end

Instance Attribute Details

#backgroundBoolean? (readonly)

Returns whether this is a background response.

Returns:

  • (Boolean, nil)

    whether this is a background response



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#completed_atInteger? (readonly)

Returns completion timestamp.

Returns:

  • (Integer, nil)

    completion timestamp



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#created_atInteger? (readonly)

Returns creation timestamp.

Returns:

  • (Integer, nil)

    creation timestamp



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#errorHash? (readonly)

Returns error information.

Returns:

  • (Hash, nil)

    error information



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#extraObject (readonly) Also known as: provider_data

Returns the value of attribute extra.



128
129
130
# File 'lib/prompt_builder/response.rb', line 128

def extra
  @extra
end

#frequency_penaltyFloat? (readonly)

Returns the frequency penalty.

Returns:

  • (Float, nil)

    the frequency penalty



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#idString? (readonly)

Returns the response identifier.

Returns:

  • (String, nil)

    the response identifier



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#incomplete_detailsHash? (readonly)

Returns details about why the response is incomplete.

Returns:

  • (Hash, nil)

    details about why the response is incomplete



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#instructionsString? (readonly)

Returns the system instructions.

Returns:

  • (String, nil)

    the system instructions



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#max_output_tokensInteger? (readonly)

Returns the maximum output tokens.

Returns:

  • (Integer, nil)

    the maximum output tokens



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#max_tool_callsInteger? (readonly)

Returns the maximum number of tool calls.

Returns:

  • (Integer, nil)

    the maximum number of tool calls



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#metadataHash? (readonly)

Returns arbitrary metadata.

Returns:

  • (Hash, nil)

    arbitrary metadata



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#modelString? (readonly)

Returns the model identifier.

Returns:

  • (String, nil)

    the model identifier



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#objectString? (readonly)

Returns the object type.

Returns:

  • (String, nil)

    the object type



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#outputArray<Items::Base> (readonly)

Returns the output items.

Returns:



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#parallel_tool_callsBoolean? (readonly)

Returns whether parallel tool calls are enabled.

Returns:

  • (Boolean, nil)

    whether parallel tool calls are enabled



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#presence_penaltyFloat? (readonly)

Returns the presence penalty.

Returns:

  • (Float, nil)

    the presence penalty



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#previous_response_idString? (readonly)

Returns the previous response identifier.

Returns:

  • (String, nil)

    the previous response identifier



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#prompt_cache_keyString? (readonly)

Returns the prompt cache key.

Returns:

  • (String, nil)

    the prompt cache key



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#prompt_cache_retentionString? (readonly)

Returns the prompt cache retention policy.

Returns:

  • (String, nil)

    the prompt cache retention policy



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#reasoningHash? (readonly)

Returns the reasoning configuration.

Returns:

  • (Hash, nil)

    the reasoning configuration



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#safety_identifierString? (readonly)

Returns the safety identifier.

Returns:

  • (String, nil)

    the safety identifier



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#service_tierString? (readonly)

Returns the service tier.

Returns:

  • (String, nil)

    the service tier



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#statusString? (readonly)

Returns the response status.

Returns:

  • (String, nil)

    the response status



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#storeBoolean? (readonly)

Returns whether to store the response.

Returns:

  • (Boolean, nil)

    whether to store the response



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#temperatureFloat? (readonly)

Returns the temperature.

Returns:

  • (Float, nil)

    the temperature



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#text_configHash? (readonly)

Returns the text configuration.

Returns:

  • (Hash, nil)

    the text configuration



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#tool_choiceString, ... (readonly)

Returns the tool choice configuration.

Returns:

  • (String, Hash, nil)

    the tool choice configuration



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#toolsArray<Hash>? (readonly)

Returns the tool definitions.

Returns:

  • (Array<Hash>, nil)

    the tool definitions



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#top_logprobsInteger? (readonly)

Returns the number of top log probabilities to return.

Returns:

  • (Integer, nil)

    the number of top log probabilities to return



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#top_pFloat? (readonly)

Returns the top_p sampling parameter.

Returns:

  • (Float, nil)

    the top_p sampling parameter



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#truncationString? (readonly)

Returns the truncation strategy.

Returns:

  • (String, nil)

    the truncation strategy



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

#usageUsage? (readonly)

Returns token usage statistics.

Returns:

  • (Usage, nil)

    token usage statistics



127
# File 'lib/prompt_builder/response.rb', line 127

FIELDS.each { |f| attr_reader f }

Class Method Details

.from_h(hash) ⇒ Response

Deserialize a Response from a Hash.

Parameters:

  • hash (Hash)

    a Hash with string keys from the API response

Returns:



171
172
173
174
175
176
177
# File 'lib/prompt_builder/response.rb', line 171

def from_h(hash)
  output = (hash["output"] || []).map { |item| Items::Base.from_h(item) }
  usage = hash["usage"] ? Usage.from_h(hash["usage"]) : nil

  attrs = FIELDS.each_with_object({}) { |f, acc| acc[f] = hash[f.to_s] }
  new(**attrs, text_config: hash["text"], output: output, usage: usage, extra: hash["extra"])
end

.from_text(text, status: "completed", **attributes) ⇒ Response

Synthesize a Response containing a single assistant text message. Useful for canned answers (halt messages, cached responses) and tests without assembling Items::Message and Content::OutputText by hand.

Examples:

PromptBuilder::Response.from_text("Authentication failed.",
  model: llm_response.model, usage: llm_response.usage)

Parameters:

  • text (String)

    the assistant message text

  • status (String) (defaults to: "completed")

    the response status

  • attributes (Hash)

    any other Response attributes (e.g. model, usage, id)

Returns:



191
192
193
194
# File 'lib/prompt_builder/response.rb', line 191

def from_text(text, status: "completed", **attributes)
  message = Items::Message.new(role: "assistant", content: [Content::OutputText.new(text: text)])
  new(status: status, output: [message], **attributes)
end

.parse(hash, serializer_class) ⇒ Response

Parse a response hash using the given serializer and return a Response.

Parameters:

  • hash (Hash)

    the API response hash (typically from JSON.parse)

  • serializer_class (Class, Symbol)

    a serializer class (e.g. Serializers::ChatCompletion) or a symbol shorthand (+:open_responses+, :chat_completion, :messages, :gemini, :converse)

Returns:

Raises:

  • (ArgumentError)

    if a symbol is given that does not map to a known serializer



163
164
165
# File 'lib/prompt_builder/response.rb', line 163

def parse(hash, serializer_class)
  Serializers.resolve(serializer_class).parse_response(hash)
end

Instance Method Details

#completed?Boolean

Check if the response completed successfully.

Returns:

  • (Boolean)


200
201
202
# File 'lib/prompt_builder/response.rb', line 200

def completed?
  @status == "completed"
end

#failed?Boolean

Check if the response failed.

Returns:

  • (Boolean)


207
208
209
# File 'lib/prompt_builder/response.rb', line 207

def failed?
  @status == "failed"
end

#has_tool_calls?Boolean

Check if the response contains any tool calls.

Returns:

  • (Boolean)


221
222
223
# File 'lib/prompt_builder/response.rb', line 221

def has_tool_calls?
  @output.any? { |item| item.is_a?(Items::FunctionCall) }
end

#incomplete?Boolean

Check if the response is incomplete.

Returns:

  • (Boolean)


214
215
216
# File 'lib/prompt_builder/response.rb', line 214

def incomplete?
  @status == "incomplete"
end

#parsed_jsonHash, ...

Parse the response text as JSON, for use with structured output (see Session#json_output). Strips a fenced ```json wrapper when present — a common provider quirk. Returns nil when the response has no text or the text is not valid JSON; use parsed_json! to raise instead.

Returns:

  • (Hash, Array, Object, nil)

    the parsed JSON value, or nil



253
254
255
256
257
258
259
260
261
262
# File 'lib/prompt_builder/response.rb', line 253

def parsed_json
  raw = text
  return nil unless raw

  begin
    JSON.parse(strip_json_fences(raw))
  rescue JSON::ParserError
    nil
  end
end

#parsed_json!Hash, ...

Parse the response text as JSON, raising when it cannot be parsed.

Returns:

  • (Hash, Array, Object)

    the parsed JSON value

Raises:

  • (ParseError)

    if the response has no text or the text is not valid JSON; the error message includes the raw text



269
270
271
272
273
274
275
276
277
278
# File 'lib/prompt_builder/response.rb', line 269

def parsed_json!
  raw = text
  raise ParseError, "Response has no text output to parse as JSON" unless raw

  begin
    JSON.parse(strip_json_fences(raw))
  rescue JSON::ParserError => e
    raise ParseError, "Response text is not valid JSON (#{e.message}); raw text: #{raw}"
  end
end

#textString?

Extract the text from the first output message. Returns the concatenated text of all OutputText content blocks in the first message.

Returns:

  • (String, nil)

    the text content, or nil if no message with text is found



236
237
238
239
240
241
242
243
244
# File 'lib/prompt_builder/response.rb', line 236

def text
  @output.each do |item|
    next unless item.is_a?(Items::Message)

    texts = item.content.select { |c| c.is_a?(Content::OutputText) }
    return texts.map(&:text).join unless texts.empty?
  end
  nil
end

#to_hHash

Serialize to a Hash with string keys. Nil values are omitted.

Returns:

  • (Hash)


283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/prompt_builder/response.rb', line 283

def to_h
  h = {}
  FIELDS.each do |f|
    val = instance_variable_get(:"@#{f}")
    if BOOLEAN_FIELDS.include?(f)
      h[f.to_s] = val unless val.nil?
    elsif val
      h[f.to_s] = val
    end
  end
  h["text"] = @text_config if @text_config
  h["output"] = @output.map(&:to_h) unless @output.empty?
  h["usage"] = @usage.to_h if @usage
  h["extra"] = @extra if @extra && !@extra.empty?
  h
end

#tool_callsArray<Items::FunctionCall>

Get all function call items from the output.

Returns:



228
229
230
# File 'lib/prompt_builder/response.rb', line 228

def tool_calls
  @output.select { |item| item.is_a?(Items::FunctionCall) }
end