Class: AsktiveRecord::LlmService

Inherits:
Object
  • Object
show all
Defined in:
lib/asktive_record/llm_service.rb

Overview

Service class for interacting with the LLM API to generate SQL queries and answer questions based on the generated queries and database responses. Uses the adapter pattern to support multiple LLM providers.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ LlmService

Returns a new instance of LlmService.

Raises:



13
14
15
16
17
18
19
20
21
22
# File 'lib/asktive_record/llm_service.rb', line 13

def initialize(configuration)
  @configuration = configuration
  @adapter = nil

  return if @configuration&.llm_api_key

  raise ConfigurationError,
        "LLM API key is not configured. Please set it in config/initializers/asktive_record.rb " \
        "or via environment variable."
end

Instance Attribute Details

#configurationObject (readonly)

Returns the value of attribute configuration.



11
12
13
# File 'lib/asktive_record/llm_service.rb', line 11

def configuration
  @configuration
end

Instance Method Details

#answer(question, query, response) ⇒ Object



32
33
34
35
36
37
# File 'lib/asktive_record/llm_service.rb', line 32

def answer(question, query, response)
  AsktiveRecord::Log.info("Answering question: #{question}")
  AsktiveRecord::Log.debug("Generated SQL query: #{query}")
  AsktiveRecord::Log.debug("Response from database: #{response.inspect}")
  answer_as_human(question, query, response)
end

#generate_sql(natural_language_query, schema_string, table_name) ⇒ Object

Method for model-specific queries



40
41
42
43
44
45
46
47
48
# File 'lib/asktive_record/llm_service.rb', line 40

def generate_sql(natural_language_query, schema_string, table_name)
  prompt = Prompt.as_sql_generator_for_model(
    natural_language_query,
    schema_string,
    table_name
  )

  generate_and_validate_sql(prompt)
end

#generate_sql_for_service(natural_language_query, schema_string, _target_table = "any") ⇒ Object

Method for service-class-based queries that can target any table



51
52
53
54
# File 'lib/asktive_record/llm_service.rb', line 51

def generate_sql_for_service(natural_language_query, schema_string, _target_table = "any")
  prompt = Prompt.as_sql_generator(natural_language_query, schema_string)
  generate_and_validate_sql(prompt)
end

#upload_schema(_schema_string) ⇒ Object

Placeholder for schema upload/management with the LLM if needed for more advanced scenarios. For instance, if using OpenAI Assistants API or fine-tuning. For now, the schema is passed with each query.



27
28
29
30
# File 'lib/asktive_record/llm_service.rb', line 27

def upload_schema(_schema_string)
  AsktiveRecord::Log.info("Schema upload functionality is a placeholder for now.")
  true
end