Class: Instructor::OpenAI::Response

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

Overview

The Response class represents the response received from the OpenAI API. It takes the raw response and provides convenience methods to access the chat completions, tool calls, function responses, and parsed arguments.

Instance Method Summary collapse

Constructor Details

#initialize(response) ⇒ Response

Initializes a new instance of the Response class.

Parameters:

  • response (Hash)

    The response received from the OpenAI API.



12
13
14
# File 'lib/instructor/openai/response.rb', line 12

def initialize(response)
  @response = response
end

Instance Method Details

#by_function_name(function_name) ⇒ Hash?

Returns the arguments of the function with the specified name.

Parameters:

  • function_name (String)

    The name of the function.

Returns:

  • (Hash, nil)

    The arguments of the function or nil if not found.



66
67
68
# File 'lib/instructor/openai/response.rb', line 66

def by_function_name(function_name)
  function_responses&.find { |res| res['name'] == function_name }&.dig('arguments')
end

#chat_completionsArray

Returns the chat completions from the response.

Returns:

  • (Array)

    An array of chat completions.



19
20
21
# File 'lib/instructor/openai/response.rb', line 19

def chat_completions
  @response['choices']
end

#function_responseHash?

Returns the first function response.

Returns:

  • (Hash, nil)

    The first function response or nil if not found.



40
41
42
# File 'lib/instructor/openai/response.rb', line 40

def function_response
  function_responses&.first
end

#function_responsesArray?

Returns the function responses from the tool calls.

Returns:

  • (Array, nil)

    An array of function responses or nil if not found.



33
34
35
# File 'lib/instructor/openai/response.rb', line 33

def function_responses
  tool_calls&.map { |tool_call| tool_call['function'] }
end

#parseArray, Hash

Parses the function response(s) and returns the parsed arguments.

Returns:

  • (Array, Hash)

    The parsed arguments.



54
55
56
57
58
59
60
# File 'lib/instructor/openai/response.rb', line 54

def parse
  if single_response?
    JSON.parse(function_response['arguments'])
  else
    function_responses.map { |res| JSON.parse(res['arguments']) }
  end
end

#single_response?Boolean

Checks if there is only a single function response.

Returns:

  • (Boolean)

    True if there is only a single function response, false otherwise.



47
48
49
# File 'lib/instructor/openai/response.rb', line 47

def single_response?
  function_responses&.size == 1
end

#tool_callsHash?

Returns the tool calls from the chat completions.

Returns:

  • (Hash, nil)

    The tool calls or nil if not found.



26
27
28
# File 'lib/instructor/openai/response.rb', line 26

def tool_calls
  chat_completions&.dig(0, 'message', 'tool_calls')
end