Class: Raif::Llms::OpenAi

Inherits:
Raif::Llm
  • Object
show all
Includes:
Concerns::Llms::OpenAi::MessageFormatting
Defined in:
app/models/raif/llms/open_ai.rb

Instance Method Summary collapse

Instance Method Details

#connectionObject



28
29
30
31
32
33
34
35
# File 'app/models/raif/llms/open_ai.rb', line 28

def connection
  @connection ||= Faraday.new(url: "https://api.openai.com/v1") do |f|
    f.headers["Authorization"] = "Bearer #{Raif.config.open_ai_api_key}"
    f.request :json
    f.response :json
    f.response :raise_error
  end
end

#perform_model_completion!(model_completion) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'app/models/raif/llms/open_ai.rb', line 6

def perform_model_completion!(model_completion)
  model_completion.temperature ||= default_temperature
  parameters = build_request_parameters(model_completion)

  response = connection.post("chat/completions") do |req|
    req.body = parameters
  end

  response_json = response.body

  model_completion.update!(
    response_tool_calls: extract_response_tool_calls(response_json),
    raw_response: response_json.dig("choices", 0, "message", "content"),
    completion_tokens: response_json.dig("usage", "completion_tokens"),
    prompt_tokens: response_json.dig("usage", "prompt_tokens"),
    total_tokens: response_json.dig("usage", "total_tokens"),
    response_format_parameter: parameters.dig(:response_format, :type)
  )

  model_completion
end

#validate_json_schema!(schema) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'app/models/raif/llms/open_ai.rb', line 37

def validate_json_schema!(schema)
  return if schema.blank?

  errors = []

  # Check if schema is present
  if schema.blank?
    errors << "JSON schema must include a 'schema' property"
  else
    # Check root object type
    if schema[:type] != "object" && !schema.key?(:properties)
      errors << "Root schema must be of type 'object' with 'properties'"
    end

    # Check all objects in the schema recursively
    validate_object_properties(schema, errors)

    # Check properties count (max 100 total)
    validate_properties_count(schema, errors)

    # Check nesting depth (max 5 levels)
    validate_nesting_depth(schema, errors)

    # Check for unsupported anyOf at root level
    if schema[:anyOf].present? && schema[:properties].blank?
      errors << "Root objects cannot be of type 'anyOf'"
    end
  end

  # Raise error if any validation issues found
  if errors.any?
    error_message = "Invalid JSON schema for OpenAI structured outputs: #{errors.join("; ")}\nSchema was: #{schema.inspect}"
    raise Raif::Errors::OpenAi::JsonSchemaError, error_message
  else
    true
  end
end