Is there a recommended way of parsing the content
of messages?
#12
-
Hey, first off, I really appreciate this library. It's by far the easiest to use for LLMs in Rails. Thank you! I’ve noticed that messages can have three different content formats:
Is there a recommended way to handle these formats when reading messages? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Not the most beautiful solution, but ended up with this to avoid using # Migration
add_column :messages, :message, :string
# Model
class Message < ApplicationRecord
acts_as_message
before_save :populate_message, if: -> { role == "user" || role == "assistant" && content.present? }
private
def populate_message
parsed_content = content.gsub("=>", ":").gsub(/:(\w+)/, '"\1"')
parsed_content = JSON.parse(parsed_content)
self.message = parsed_content[:message] || parsed_content["message"] if parsed_content.is_a?(Hash)
rescue SyntaxError, StandardError
self.message = content
end
end |
Beta Was this translation helpful? Give feedback.
-
Hey @diegoquiroz thank you for the kind words! Just to understand better what's happening, can you make a contrived example of how you got these different messages? |
Beta Was this translation helpful? Give feedback.
Looking at your examples, I think you're running into an issue because you're using the library in a way that wasn't intended.
The
ask()
method is designed to take a string as its first positional argument, not a set of named parameters. The API is meant to be used like this:When you do:
You're actually passing a Ruby hash as the first argument, which gets converted to a string representation and stored directly. That's why you're seeing Ruby hash syntax in your content field.
The only reason this doesn't raise …