Class: Instructor::OpenAI::Response
- Inherits:
-
Object
- Object
- Instructor::OpenAI::Response
- 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
-
#by_function_name(function_name) ⇒ Hash?
Returns the arguments of the function with the specified name.
-
#chat_completions ⇒ Array
Returns the chat completions from the response.
-
#function_response ⇒ Hash?
Returns the first function response.
-
#function_responses ⇒ Array?
Returns the function responses from the tool calls.
-
#initialize(response) ⇒ Response
constructor
Initializes a new instance of the Response class.
-
#parse ⇒ Array, Hash
Parses the function response(s) and returns the parsed arguments.
-
#single_response? ⇒ Boolean
Checks if there is only a single function response.
-
#tool_calls ⇒ Hash?
Returns the tool calls from the chat completions.
Constructor Details
#initialize(response) ⇒ Response
Initializes a new instance of the Response class.
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.
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_completions ⇒ Array
Returns the chat completions from the response.
19 20 21 |
# File 'lib/instructor/openai/response.rb', line 19 def chat_completions @response['choices'] end |
#function_response ⇒ Hash?
Returns the first function response.
40 41 42 |
# File 'lib/instructor/openai/response.rb', line 40 def function_response function_responses&.first end |
#function_responses ⇒ Array?
Returns the function responses from the tool calls.
33 34 35 |
# File 'lib/instructor/openai/response.rb', line 33 def function_responses tool_calls&.map { |tool_call| tool_call['function'] } end |
#parse ⇒ Array, Hash
Parses the function response(s) and returns 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.
47 48 49 |
# File 'lib/instructor/openai/response.rb', line 47 def single_response? function_responses&.size == 1 end |
#tool_calls ⇒ Hash?
Returns the tool calls from the chat completions.
26 27 28 |
# File 'lib/instructor/openai/response.rb', line 26 def tool_calls chat_completions&.dig(0, 'message', 'tool_calls') end |