Class: Amazon::ListingOptimizer

Inherits:
Object
  • Object
show all
Includes:
Memery
Defined in:
app/services/amazon/listing_optimizer.rb

Constant Summary collapse

AVAILABLE_MODELS =

Available AI models for listing optimization
Claude Sonnet is recommended for copywriting due to better brand voice consistency

{
  AiModelConstants.id(:amazon_listing) => 'Claude Sonnet 4.6 (Recommended)',
  'gpt-4o' => 'GPT-4o',
  'gpt-4o-mini' => 'GPT-4o Mini (Faster/Cheaper)'
}.freeze
DEFAULT_MODEL =
AiModelConstants.id(:amazon_listing)
DEFAULT_PROMPT =
<<~PROMPT

  You are an expert copywriter and specialize in optimizing product listings on Amazon.

  You write in the persuasive style of Jim Edwards.

  You will be provided a list of Target Keywords ordered by importance descending.

  The improved product listing should consist of the following elements:

  - Product title
  - 5 bullet points
  - Generic Keyword list
  - Product Description

  General rules:
  - Use correct unit formatting (e.g., 2x3 ft., 5 in., 13 sq. ft.) for the target country.

  The following rules apply to the product title:
  - The title must have a minimum of 80 and a maximum of 160 characters.
  - Mention the most important product facts and keywords within the first 50 characters of the title.
  - The brand of the item is at the beginning of the title
  - The title should be readable and not appear too choppy.
  - Use word combinations but also individual words
  - Add at least 2 highly-relevant keywords within the title

  The following rules apply to the 5 bullet points:
  - Write 5 bullet points
  - Each of the 5 bullet points must not be longer than 180 characters
  - The 5 bullet points must be at least 900 characters long in total
  - Start each paragraph with a descriptive advantage feature and then explain the product features in complete sentences
  - Use relevant keywords within the bullet points
  - Don't use third-party brands as keywords
  - The last bullet should be reserved for specifications such as the SKU, dimensions (expressed in both imperial and metric), power consumptions, warranty, certifications, ip protection rating

  The following rules apply to the generic keyword list:
  - Do not use your own or third-party brands in the keywords.
  - Each word should only appear once. Try to avoid repeating words.
  - The keyword list consists of a maximum of 500 letters or spaces.
  - Don't use commas. Separate with space.
  - Remove duplicate words.
  - Write everything in lower case.

  Compelling Product Description (1000–2000 characters)
  - Engaging, benefit-driven, and clear while seamlessly weaving in keywords.
  - Explain how the product improves the customer’s life and why it’s better than competitors.
  - No promotional language, HTML, special characters, or links.

PROMPT

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(access_token: nil, model: nil) ⇒ ListingOptimizer

Returns a new instance of ListingOptimizer.



70
71
72
73
74
75
# File 'app/services/amazon/listing_optimizer.rb', line 70

def initialize(access_token: nil, model: nil)
  @access_token = access_token || Rails.application.credentials.dig(:openai, :api_key_amazon)
  @model = model.presence || DEFAULT_MODEL
  @client = intialize_ai_client
  @prompt = DEFAULT_PROMPT
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



4
5
6
# File 'app/services/amazon/listing_optimizer.rb', line 4

def client
  @client
end

#itemObject (readonly)

Returns the value of attribute item.



4
5
6
# File 'app/services/amazon/listing_optimizer.rb', line 4

def item
  @item
end

#localeObject (readonly)

Returns the value of attribute locale.



4
5
6
# File 'app/services/amazon/listing_optimizer.rb', line 4

def locale
  @locale
end

#modelObject (readonly)

Returns the value of attribute model.



4
5
6
# File 'app/services/amazon/listing_optimizer.rb', line 4

def model
  @model
end

#product_infoObject (readonly)

Returns the value of attribute product_info.



4
5
6
# File 'app/services/amazon/listing_optimizer.rb', line 4

def product_info
  @product_info
end

#promptObject (readonly)

Returns the value of attribute prompt.



4
5
6
# File 'app/services/amazon/listing_optimizer.rb', line 4

def prompt
  @prompt
end

#responseObject (readonly)

Returns the value of attribute response.



4
5
6
# File 'app/services/amazon/listing_optimizer.rb', line 4

def response
  @response
end

#resultObject (readonly)

Returns the value of attribute result.



4
5
6
# File 'app/services/amazon/listing_optimizer.rb', line 4

def result
  @result
end

#target_keywordsObject (readonly)

Returns the value of attribute target_keywords.



4
5
6
# File 'app/services/amazon/listing_optimizer.rb', line 4

def target_keywords
  @target_keywords
end

Class Method Details

.models_for_selectObject



16
17
18
# File 'app/services/amazon/listing_optimizer.rb', line 16

def self.models_for_select
  AVAILABLE_MODELS.map { |id, name| [name, id] }
end

Instance Method Details

#analyze_keyword_density(listing) ⇒ Object



323
324
325
326
327
328
329
330
331
332
333
334
# File 'app/services/amazon/listing_optimizer.rb', line 323

def analyze_keyword_density(listing)
  target_keywords = listing[:target_keywords] || @target_keywords.presence
  return unless target_keywords.present?

  params = {
    title: listing[:product_title],
    bullet_points: listing[:bullet_points].join(' '),
    generic_keyword: listing[:generic_keyword],
    description: listing[:product_description]
  }
  Seo::KeywordAnalyzer.new.process(params, @target_keywords)
end

#brand_voice_contextObject

Brand voice context loaded from Settings (cached in Rails)
This content is ideal for Anthropic prompt caching as it's static across requests



191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'app/services/amazon/listing_optimizer.rb', line 191

def brand_voice_context
  parts = []

  guidelines = Setting.brand_voice_guidelines
  parts << "## Brand Voice Guidelines\n#{guidelines}" if guidelines.present?

  examples = Setting.brand_voice_examples
  parts << "## Example Content (follow this style)\n#{examples}" if examples.present?

  phrases_to_use = Array(Setting.brand_voice_phrases_to_use).reject(&:blank?)
  parts << "## Preferred Phrases\nUse these phrases when appropriate: #{phrases_to_use.join(', ')}" if phrases_to_use.any?

  phrases_to_avoid = Array(Setting.brand_voice_phrases_to_avoid).reject(&:blank?)
  parts << "## Phrases to Avoid\nDo NOT use these overused marketing phrases: #{phrases_to_avoid.join(', ')}" if phrases_to_avoid.any?

  parts.join("\n\n---\n\n")
end

#cacheable_prompt(text) ⇒ Object

Wrap prompt in Anthropic-native content block with cache hint.
The static prefix (DEFAULT_PROMPT + brand voice) is reused across all
items in a batch. Anthropic's prefix caching keeps it warm for 5 minutes,
reducing cost and latency for consecutive optimizations.
Non-Anthropic models receive plain text unchanged.



273
274
275
276
277
278
279
280
# File 'app/services/amazon/listing_optimizer.rb', line 273

def cacheable_prompt(text)
  return text unless model.to_s.start_with?('claude-')

  RubyLLM::Providers::Anthropic::Content.new(text, cache: true)
rescue StandardError => e
  Rails.logger.warn("[Amazon::ListingOptimizer] Prompt caching wrapper failed: #{e.message}")
  text
end

#generate_messagesObject



179
180
181
182
183
184
185
186
187
# File 'app/services/amazon/listing_optimizer.rb', line 179

def generate_messages
  messages = [{ role: 'system', content: generate_system_parameters_message }]
  # Include brand voice context (cached portion for Anthropic models)
  messages << { role: 'system', content: brand_voice_context } if brand_voice_context.present?
  messages << { role: 'system', content: "Target Keywords: #{@target_keywords}" } if @target_keywords.present?
  messages << { role: 'system', content: @product_info }
  messages << { role: 'user', content: "Now, generate an Amazon listing description for the above product in #{LocaleUtility.friendly_locale_name(@locale)}" }
  messages
end

#generate_system_parameters_messageObject



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'app/services/amazon/listing_optimizer.rb', line 210

def generate_system_parameters_message
  <<~PROMPT
    #{@prompt}
    ---
    ### **Output Format (JSON)**
    ```json
    {
      "listing": {
        "sku": "{{ sku }}",
        "product_title": "{{ product_title }}",
        "bullet_points": [
          "{{ bullet_point_1 }}",
          "{{ bullet_point_2 }}",
          "{{ bullet_point_3 }}",
          "{{ bullet_point_4 }}",
          "{{ bullet_point_5 }}"
        ],
        "generic_keyword": "{{ generic_keyword }}",
        "product_description": "{{ product_description }}",
        "target_keywords": "{{ target_keywords }}"
      }
    }
  PROMPT
end

#intialize_ai_clientObject



110
111
112
113
# File 'app/services/amazon/listing_optimizer.rb', line 110

def intialize_ai_client
  # RubyLLM is configured globally, no need to initialize a client
  # The client will be created when needed in process_items
end

#load_item(item) ⇒ Object



77
78
79
80
# File 'app/services/amazon/listing_optimizer.rb', line 77

def load_item(item)
  @item = item
  @product_info = product_specific_information(item)
end

#model_listObject



174
175
176
177
# File 'app/services/amazon/listing_optimizer.rb', line 174

def model_list
  # RubyLLM provides access to available models
  RubyLLM.models.all.map(&:id)
end

#parse_response(response) ⇒ Object



282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'app/services/amazon/listing_optimizer.rb', line 282

def parse_response(response)
  content = response.content
  return unless content.present?

  # Remove Markdown code fences if present
  content = content.gsub(/\A```json\s*|```\z|```/m, '').strip

  begin
    JSON.parse(content).deep_symbolize_keys
  rescue JSON::ParserError => e
    Rails.logger.error "Failed to parse AI response as JSON: #{e.message}"
    nil
  end
end

#post_process(result) ⇒ Object



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'app/services/amazon/listing_optimizer.rb', line 297

def post_process(result)
  # The parsed response will include
  # {
  #   listing: {
  #     sku: "{{ sku }}",
  #     product_title: "{{ product_title }}",
  #     bullet_points: [
  #       "{{ bullet_point_1 }}",
  #       "{{ bullet_point_2 }}",
  #       "{{ bullet_point_3 }}",
  #       "{{ bullet_point_4 }}",
  #       "{{ bullet_point_5 }}"
  #     ],
  #     generic_keyword: "{{ generic_keyword }}",
  #     product_description: "{{ product_description }}"
  #   }
  # }
  # What will now happen is we will find references to dynamic token variables and substitute them.
  listing = result[:response][:listing]
  string_templatizer(listing[:product_title])
  listing[:bullet_points].each { |bp| string_templatizer(bp) }
  string_templatizer(listing[:product_description])
  result[:keyword_analysis] = analyze_keyword_density(listing)
  listing
end

#prepare_target_keywords(target_keywords) ⇒ Object

private



97
98
99
100
101
102
103
104
105
106
107
108
# File 'app/services/amazon/listing_optimizer.rb', line 97

def prepare_target_keywords(target_keywords)
  keywords_array = if target_keywords.is_a?(Array)
                     target_keywords
                   elsif target_keywords.present? # Cleanup and normalize separator
                     target_keywords.split(/[\n,;]/)
                   else
                     []
                   end
  keywords_array = keywords_array.filter_map { |s| s.strip.presence }.uniq
  keywords_array.reject! { |k| k.match?(/(Schluter|Ditra|Laticrete|Nuheat|SunTouch|Luxheat|Warmup|Easy Heat|Warming Systems|Thermosoft)/i) }
  keywords_array.join(',').presence
end

#process(item: nil, prompt: nil, locale: 'en-US', target_keywords: nil, link_to_product_line: nil, save_target_keywords: false, update_item: false) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
# File 'app/services/amazon/listing_optimizer.rb', line 82

def process(item: nil, prompt: nil, locale: 'en-US', target_keywords: nil, link_to_product_line: nil, save_target_keywords: false, update_item: false)
  load_item(item) if item.present?
  @prompt = prompt.presence || DEFAULT_PROMPT
  @locale = locale.to_sym
  @response = nil
  @link_to_product_line = item.amazon_variation.present? if link_to_product_line.nil?
  @save_target_keywords = save_target_keywords
  target_keywords ||= item.amazon_target_keywords
  @target_keywords = prepare_target_keywords(target_keywords)
  @update_item = update_item
  process_items
end

#process_itemsObject



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'app/services/amazon/listing_optimizer.rb', line 115

def process_items
  messages = generate_messages

  # Create RubyLLM chat instance (assume_model_exists so registry lookup is optional)
  provider = model.start_with?('claude-') ? :anthropic : :openai
  chat = RubyLLM.chat(model: model, provider: provider, assume_model_exists: true)
  chat.with_temperature(0.7)

  # Convert messages to RubyLLM format
  system_messages = messages.select { |m| m[:role] == 'system' }
  user_messages = messages.select { |m| m[:role] == 'user' }

  # Add system messages as instructions.
  # The static prefix (prompt template + brand voice) is wrapped for Anthropic
  # prompt caching so consecutive item optimizations reuse the cached prefix.
  # Messages after the static cutoff (target keywords, product info) are
  # dynamic per item and sent as plain text.
  static_count = brand_voice_context.present? ? 2 : 1
  system_messages.each_with_index do |msg, idx|
    content = msg[:content]
    content = cacheable_prompt(content) if idx == static_count - 1
    chat.with_instructions(content)
  end

  # Add user message and get response
  user_content = user_messages.map { |m| m[:content] }.join("\n")
  response = RubyLLM::Instrumentation.with(feature: 'amazon_listing') do
    chat.ask(user_content)
  end

  result = {
    parameters: {
      model: model,
      messages: messages,
      temperature: 0.7
    },
    target_keywords: @target_keywords,
    response: parse_response(response)
  }

  # In case we generated our own keywords lets save them back here
  @target_keywords = result.dig(:response, :listing, :target_keywords) if @target_keywords.blank?
  post_process(result)
  save_results_to_item(result) if @update_item
  result
rescue RubyLLM::RateLimitError => e
  Rails.logger.warn "[ListingOptimizer] Rate limited for Item #{item&.id}: #{e.message}"
  raise
rescue RubyLLM::ContextLengthExceededError => e
  Rails.logger.error "[ListingOptimizer] Context too long for Item #{item&.id}: #{e.message}"
  raise
rescue RubyLLM::UnauthorizedError => e
  Rails.logger.error "[ListingOptimizer] Auth failure: #{e.message}"
  raise
rescue RubyLLM::Error => e
  Rails.logger.error "[ListingOptimizer] RubyLLM error for Item #{item&.id}: #{e.message}"
  raise
end

#product_specific_information(item) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'app/services/amazon/listing_optimizer.rb', line 235

def product_specific_information(item)
  product_data = <<~PROMPT
    Product Specific Information
    sku: #{item.sku}
    current amazon title: #{item.amazon_title}
    current amazon bullet points: #{item.amazon_features}
    current amazon description: #{item.amazon_description}
    current amazon generic keyword: #{item.amazon_generic_keyword}
    ---
    Product Details
    model name: #{item.spec_output(:model_name)}
    brand: WarmlyYours
    product line: #{item.primary_product_line&.lineage_expanded}
    product category: #{item.product_category&.lineage_expanded}
    public name: #{item.public_name}
    public description: #{item.public_description_text}
    public features: #{item.features}
    product line description: #{item.primary_product_line&.description}
    product line features: #{item.primary_product_line&.features&.join("\n")}
  PROMPT
  token_specs.each { |k, v| product_data << "#{k}: #{v}\n" }
  product_data
end

#save_results_to_item(result) ⇒ Object



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
# File 'app/services/amazon/listing_optimizer.rb', line 349

def save_results_to_item(result)
  listing = result[:response][:listing]
  # Make sure our result set is complete
  product_title = listing[:product_title].presence
  bullet_points = listing[:bullet_points].presence
  generic_keyword = listing[:generic_keyword].presence
  product_description = listing[:product_description].presence
  return { status: :listing_incomplete, message: 'product_tite, bullet_points, generic_keyword, or product_description mising' } unless product_title.present? && bullet_points.present? && generic_keyword.present? && product_description.present?

  @item.create_or_set_amazon_spec_value(name: 'Title', text_blurb: listing[:product_title], link_to_product_line: @link_to_product_line) if listing[:product_title].present?
  listing[:bullet_points].each_with_index do |bp, i|
    @item.create_or_set_amazon_spec_value(name: "Feature #{i + 1}", text_blurb: bp, link_to_product_line: @link_to_product_line) if bp.present?
  end
  @item.create_or_set_amazon_spec_value(name: 'Keywords', text_blurb: listing[:generic_keyword], link_to_product_line: @link_to_product_line) if listing[:generic_keyword].present?
  @item.create_or_set_amazon_spec_value(name: 'Description', text_blurb: listing[:product_description], link_to_product_line: @link_to_product_line) if listing[:product_description].present?
  @item.create_or_set_amazon_spec_value(name: 'Target Keywords', text_blurb: @target_keywords, link_to_product_line: @link_to_product_line) if @save_target_keywords
  @item.update_rendered_product_specifications
  { status: :success, message: 'Item updated with new specs' }
end

#string_templatizer(string) ⇒ Object



336
337
338
339
340
341
342
343
344
345
346
347
# File 'app/services/amazon/listing_optimizer.rb', line 336

def string_templatizer(string)
  return if string.blank?

  observed_tokens = %i[sku amps color watts width length depth height voltage coverage warranty amazon_size heating_cable_length amazon_heating_coverage]
  token_specs.slice(*observed_tokens).each do |token, value|
    next if value.blank?

    # We're going to try a few permutation of the value
    string.gsub!(value, "{{ #{token} }}")
  end
  string
end

#token_specsObject



259
260
261
262
263
264
265
# File 'app/services/amazon/listing_optimizer.rb', line 259

def token_specs
  excluded_tokens = %i[amazon_feature_1 amazon_feature_2 amazon_feature_3 amazon_feature_4 amazon_feature_5
                       amazon_generic_keyword amazon_description amazon_title]
  specs = @item.token_specs_values_for_liquid(include_legacy: false).symbolize_keys
  # Remove redundant attributes, no need to waste good tokens on these
  specs.reject { |k, v| v.blank? || k.in?(excluded_tokens) || k.to_s.ends_with?('_raw') || k.to_s.ends_with?('_units') }
end