Enhancing the Trix Editor in Rails with AI-Powered Orthographic Correction
Introduction
When working with rich text editors in Ruby on Rails applications, enhancing usability is a key factor. Trix is a powerful WYSIWYG editor, but what if we could take it a step further by integrating AI-powered orthographic correction? In this article, I'll walk you through how I built a feature that allows users to correct spelling and grammar mistakes in a Trix editor using DeepSeek AI.
Want to Add AI to Your Rails Project?
Do you need AI integration in your Rails project? Let's work together to improve your application! Get in touch here. ??
Prerequisites
Before diving into this integration, I highly recommend checking out these two articles:
Once you're comfortable with these setups, we can move forward with integrating DeepSeek for orthographic correction.
Adding a Custom Button to the Trix Editor
Using StimulusJS, we can extend the Trix toolbar to include a new button for correcting orthography. Here's how you can achieve this:
app/javascript/controllers/trix-controller.js
import { Controller } from "@hotwired/stimulus";
export default class extends Controller {
connect() {
addEventListener("trix-initialize", (event) => {
const trixEditor = event.target;
const aiButton = document.createElement("button");
aiButton.setAttribute("type", "button");
aiButton.setAttribute("title", "Correct Orthography");
aiButton.classList.add("trix-button");
aiButton.innerHTML = `
<svg xmlns="https://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
<path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/>
</svg>
`;
document.querySelector(".trix-button-group--text-tools").appendChild(aiButton);
aiButton.addEventListener("click", () => {
this.correctOrthography(trixEditor);
});
});
}
async correctOrthography(trixEditor) {
try {
const editor = trixEditor.editor;
const content = editor.getDocument().toString();
const response = await fetch("/orthography/correct", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: content }),
});
if (!response.ok) {
throw new Error("Network response was not ok");
}
const result = await response.json();
editor.loadHTML(result.corrected_text);
} catch (error) {
console.error("Error correcting orthography:", error);
alert("An error occurred while correcting orthography.");
}
}
}
Backend: Creating the Orthography Correction API
Now, let's create a controller to handle the correction requests by integrating DeepSeek AI.
app/controllers/orthography_controller.rb
class OrthographyController < ApplicationController
skip_before_action :verify_authenticity_token
def correct
text = params.require(:text)
corrected_text = call_ai_service(text)
render json: { corrected_text: corrected_text }
rescue StandardError => e
Rails.logger.error("Orthography Correction Error: #{e.message}")
render json: { error: "An error occurred while correcting orthography." }, status: :unprocessable_entity
end
private
def call_ai_service(text)
headers = {
'Content-Type' => 'application/json',
'Authorization' => "Bearer #{ENV['DEEPSEEK_API_KEY']}"
}
body = {
model: "deepseek-chat",
messages: [{ role: "user", content: "Correct this text: #{text}" }],
temperature: 0.7,
max_tokens: 500
}.to_json
response = Faraday.post(ENV['API_URL'], body, headers)
if response.success?
return JSON.parse(response.body)['choices'][0]['message']['content']
else
"Error: #{response.status} - #{response.body}"
end
end
end
config/routes.rb
post "orthography/correct", to: "orthography#correct"
Setting Up the Environment Variables
Since we're using an external API, we need to store our API key securely. Add the following environment variables in your docker-compose.yml file:
docker-compose.yml
rails:
environment:
- DEEPSEEK_API_KEY=<YOUR_API_KEY>
- API_URL=https://api.deepseek.com/v1/chat/completions
Conclusion
By following these steps, we've successfully integrated AI-powered orthographic correction into the Trix editor within a Rails application. This feature enhances the writing experience by providing users with real-time spelling and grammar corrections powered by DeepSeek.
If you're looking to streamline your Rails development process, don't forget to check out the prerequisite articles on Dockerizing Rails and enhancing the Trix editor. Together, these enhancements make for a more efficient and user-friendly application!
Would love to hear your thoughts—feel free to comment or share! ??
? Enhance Your Trix Editor with AI-powered Correction ?
In my Complete article, you’ll find the complete repository with all the code needed to integrate AI-driven orthographic correction in the Trix editor ????.