class TableIdentifier def initialize(query:) @query = query end
def call chat end
private
def chat Llm::Chat.new(payload: chat_payload).call end
def chat_payload { "model": "gpt-4", "messages": [ { "role": "system", "content": Prompts::TABLE_IDENTIFICATION }, { "role": "user", "content": @query } ], "max_tokens": 100 } endend
module Prompts TABLE_IDENTIFICATION = "Given a user query, determine the most relevant table or tables from [users, departments, tickets]. If the query involves multiple tables (e.g., grouping users by department), return a comma-separated list of table names. Only return the table name(s) with no extra text."end
class ReportGenerator require "#{Rails.root}/lib/llm"
def initialize(query:) @query = query end
def call report end
private
def report [ { type: "text", data: "Here is your report" }, { type: "table", data: ActiveRecord::Base.connection.select_all(query).to_a } ] end
def table_structure ActiveRecord::Base.connection.execute("SHOW CREATE TABLE #{table_name}").first[1] end
def table_name TableIdentifier.new(query: @query).call end
def query Llm::Chat.new(payload: query_payload).call end
def query_payload { "model": "gpt-4", "messages": [ { "role": "system", "content": Prompts::SQL_GENERATION % { table_structure: table_structure } }, { "role": "user", "content": @query } ], "max_tokens": 1000 } endend
module Prompts SQL_GENERATION = "Generate a MySQL query based on the table structure: %{table_structure}. Support queries involving multiple tables where applicable (e.g., grouping users by department). Only return the SQL query as plain text with no formatting, explanations, or markdown."end
Tên bảng | Cấu trúc |
---|---|
users (👥) | id, name, email, status, department_id, timestamps |
departments (🏢) | id, name, manager_id, timestamps |
tickets (🎫) | id, user_id, subject, status, timestamps |
CREATE TABLE users ( id INT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255), status VARCHAR(50), department_id INT, created_at TIMESTAMP, updated_at TIMESTAMP);
ReportGenerator.new(query: "count of inactive users").callReportGenerator.new(query: "list of active users").callReportGenerator.new(query: "number of users per department").call
"count of inactive users"
, hệ thống có thể sinh câu:SELECT COUNT(*) FROM users WHERE status = 'inactive';
"number of users per department"
, câu tạo ra có thể là:SELECT d.name, COUNT(u.id)FROM users uJOIN departments d ON u.department_id = d.idGROUP BY d.name;