Class: CodeToQuery::Providers::OpenAI

Inherits:
Base
  • Object
show all
Defined in:
lib/code_to_query/providers/openai.rb

Constant Summary collapse

API_BASE =
'https://api.openai.com/v1'

Instance Attribute Summary

Attributes inherited from Base

#metrics

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from CodeToQuery::Providers::Base

Instance Method Details

#extract_intent(prompt:, schema:, allow_tables:) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/code_to_query/providers/openai.rb', line 13

def extract_intent(prompt:, schema:, allow_tables:)
  @schema = schema || {}
  @glossary = begin
    @schema['glossary'] || {}
  rescue StandardError
    {}
  end
  candidate_tables = select_context_tables(prompt, allow_tables)
  context = build_system_context(schema, candidate_tables)

  started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  response = make_api_request(
    messages: build_messages(prompt, context),
    functions: [intent_extraction_function],
    function_call: { name: 'extract_query_intent' }
  )
  elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at

  function_call = response.dig('choices', 0, 'message', 'function_call')
  intent_json = JSON.parse(function_call['arguments'])

  normalized = enhance_with_schema(intent_json, allow_tables: allow_tables, prompt_text: prompt)

  normalized['limit'] = @config.default_limit if @config.default_limit
  result = validate_and_enhance_intent(normalized, allow_tables)

  usage = response['usage'] || {}
  @metrics[:prompt_tokens] = usage['prompt_tokens']
  @metrics[:completion_tokens] = usage['completion_tokens']
  @metrics[:total_tokens] = usage['total_tokens']
  @metrics[:elapsed_s] = elapsed

  result
end