Let's face it, fellow Rails devs: a lot of what we do is just basic CRUD. We spend most of our days translating user requests into queries that hit our database. And let's be real, we're not animals - we're not writing raw SQL. No, we dress that baby up with some shiny Active Record calls to make it look pretty. But what if I told you there's an even better way to do this? Yes, my friends, we're talking about using the power of LLM (that's large language models, for those not in the know) to easily take our user queries and turn them into Active Record calls. And today, we're going to look at not one, not two, but three different methods for doing just that. Buckle up, folks - we're about to turn your code from basic to boss with these query-tastic solutions!
To demonstrate how to use the power of the LLM to enhance your app, we will be working with a simple Rails app called the [rails-railx-tailwind starter kit](https://github.com/ralixjs/rails-ralix-tailwind). This starter kit consists of two models: User
and Article
, with a one-to-many association between them. The source code for this app is available on GitHub. Let's dive in and explore how we can add AI to this app!
Here's the code for the User
and Article
models:
class User < ApplicationRecord
has_many :articles, dependent: :destroy
end
class Article < ApplicationRecord
belongs_to :user
end
It's time to dive into the first method of bringing some AI goodness into our Rails apps! And we're not talking about sprinkling some machine learning fairy dust on top - we're talking real, honest-to-goodness artificial intelligence powered by ChatGPT. And the best part? We don't have to do all the heavy lifting ourselves, because an open-source gem called Boxcars makes it a snap. Just add the gem, make a quick call, and watch as Boxcars takes care of all the parsing and handling the AI magic for you. It's like having your own personal AI assistant without having to pay them a salary. Check it out:
require 'boxcars'
ar_boxcar = Boxcars::ActiveRecord.new(code_only: true)
puts ar_boxcar.conduct("How many articles has John written?").to_h[:code]
3 simple lines of code, and our work is done.
We'll get back something like: User.where(name: "John").joins(:articles).count
All you DIY enthusiasts out there, get ready to flex those coding muscles! Our next method for using ChatGPT to write ActiveRecord queries in Rails requires a little elbow grease, but don't worry - it's nothing you can't handle. We're going to roll up our sleeves and make the API call to OpenAI ourselves, manage the prompt, and parse the output. No Boxcars to hold our hands this time, just pure unadulterated AI power. Let's take a look at the code:"
require 'openai'
client = OpenAI::Client.new(access_token: "your-token")
PROMPT = <<~IPT
Given the following Active Record models:
class User < ApplicationRecord
has_many :articles, dependent: :destroy
end
class Article < ApplicationRecord
belongs_to :user
end
Please write me an Active Record query that returns the answer to the following question.
Only reply with the Active Record query
Question: How many articles has John written?
IPT
response = client.chat(
parameters: {
model: "gpt-3.5-turbo", # Required.
messages: [{ role: "user", content: PROMPT}], # Required.
temperature: 0.7,
})
puts response.dig("choices", 0, "message", "content")
We'll get back something like: User.where(name: "John").joins(:articles).count
So here's the deal: we're using the openai
Ruby gem to make the API call to ChatGPT. First, we set our OpenAI access token- don't forget to replace 'your-token' with your actual key, or else things are going to break. Next, we provide a prompt for ChatGPT and set a temperature of 0.7
Once we make the API call, we'll get a response that contains the answer. We'll have our shiny new ActiveRecord query ready to use. Go ahead, give it a spin!
Are you a smooth talker? Then this method is for you. Forget about APIs and coding; we're going to have a one-on-one conversation with ChatGPT. It's like talking to a friend; only this friend is an LLM with impressive programming skills.
Here's how it works: head over to [https://chat.openai.com/chat](https://chat.openai.com/chat), type in the following prompt, and let your conversational skills do the rest:
Given the following Active Record models:
class User < ApplicationRecord
has_many :articles, dependent: :destroy
end
class Article < ApplicationRecord
belongs_to :user
end
Please write me an Active Record query that returns the answer to the following question.
Question: How many articles has John written?
After a bit of chitchat, ChatGPT will give you the goods:
johns_article_count = User.joins(:articles).where("users.name = ?", "John").count(:articles)
puts "John has written #{johns_article_count} articles"
So put on your smooth-talking hat and get ready to charm ChatGPT into giving you the Active Record query you need.
In conclusion, adding AI features to Rails apps is becoming more accessible with tools like Boxcars and openai gem. We also explored a manual approach to interacting with the LLM by chatting directly with ChatGPT on the OpenAI website. With these three methods at our disposal, we can leverage the power of AI to help us write Active Record queries more efficiently and effectively. By combining the domain-specific knowledge of our apps with the natural language processing capabilities of the LLM, we can unlock new possibilities in Rails development. So go ahead, try it, and see what kind of Active Record queries you can come up with!
Want these insights delivered? Subscribe below.