Class: Amazon::ListingOptimizer

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

Overview

Service object: listing optimizer.

Constant Summary collapse

AVAILABLE_MODELS =

Available AI models for listing optimization — Claude only (OpenAI dropped;
Gemini avoided for long-form copywriting). Opus is recommended for the
strongest brand voice; Sonnet is the faster/cheaper option. Ids come from
the registry.

{
  AiModelConstants.id(:amazon_listing) => 'Claude Opus 4.8 (Recommended)',
  AiModelConstants.id(:anthropic_sonnet) => 'Claude Sonnet 4.6 (Faster/Cheaper)'
}.freeze
DEFAULT_MODEL =

Default model.

AiModelConstants.id(:amazon_listing)
DEFAULT_PROMPT =

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(model: nil) ⇒ ListingOptimizer

Returns a new instance of ListingOptimizer.



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

def initialize(model: nil)
  @model = model.presence || DEFAULT_MODEL
  @prompt = DEFAULT_PROMPT
end

Instance Attribute Details

#itemObject (readonly)

Returns the value of attribute item.



7
8
9
# File 'app/services/amazon/listing_optimizer.rb', line 7

def item
  @item
end

#localeObject (readonly)

Returns the value of attribute locale.



7
8
9
# File 'app/services/amazon/listing_optimizer.rb', line 7

def locale
  @locale
end

#modelObject (readonly)

Returns the value of attribute model.



7
8
9
# File 'app/services/amazon/listing_optimizer.rb', line 7

def model
  @model
end

#product_infoObject (readonly)

Returns the value of attribute product_info.



7
8
9
# File 'app/services/amazon/listing_optimizer.rb', line 7

def product_info
  @product_info
end

#promptObject (readonly)

Returns the value of attribute prompt.



7
8
9
# File 'app/services/amazon/listing_optimizer.rb', line 7

def prompt
  @prompt
end

#responseObject (readonly)

Returns the value of attribute response.



7
8
9
# File 'app/services/amazon/listing_optimizer.rb', line 7

def response
  @response
end

#resultObject (readonly)

Returns the value of attribute result.



7
8
9
# File 'app/services/amazon/listing_optimizer.rb', line 7

def result
  @result
end

#target_keywordsObject (readonly)

Returns the value of attribute target_keywords.



7
8
9
# File 'app/services/amazon/listing_optimizer.rb', line 7

def target_keywords
  @target_keywords
end

Class Method Details

.models_for_selectObject



21
22
23
# File 'app/services/amazon/listing_optimizer.rb', line 21

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

Instance Method Details

#analyze_keyword_density(listing) ⇒ Object



331
332
333
334
335
336
337
338
339
340
341
342
# File 'app/services/amazon/listing_optimizer.rb', line 331

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

  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



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'app/services/amazon/listing_optimizer.rb', line 199

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).compact_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).compact_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.



281
282
283
284
285
286
287
288
# File 'app/services/amazon/listing_optimizer.rb', line 281

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



187
188
189
190
191
192
193
194
195
# File 'app/services/amazon/listing_optimizer.rb', line 187

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



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
# File 'app/services/amazon/listing_optimizer.rb', line 218

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

#load_item(item) ⇒ Object



81
82
83
84
# File 'app/services/amazon/listing_optimizer.rb', line 81

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

#model_listObject



182
183
184
185
# File 'app/services/amazon/listing_optimizer.rb', line 182

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

#parse_response(response) ⇒ Object



290
291
292
293
294
295
296
297
298
299
300
301
302
303
# File 'app/services/amazon/listing_optimizer.rb', line 290

def parse_response(response)
  content = response.content
  return if content.blank?

  # 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



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'app/services/amazon/listing_optimizer.rb', line 305

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



101
102
103
104
105
106
107
108
109
110
111
112
# File 'app/services/amazon/listing_optimizer.rb', line 101

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



86
87
88
89
90
91
92
93
94
95
96
97
# File 'app/services/amazon/listing_optimizer.rb', line 86

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



114
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
173
174
175
176
177
178
179
180
# File 'app/services/amazon/listing_optimizer.rb', line 114

def process_items
  messages = generate_messages

  # Create RubyLLM chat instance (assume_model_exists so registry lookup is optional).
  # Provider is inferred from the model id via the canonical registry. Fail fast on
  # an unknown id rather than silently misrouting a stale/typoed model to a default
  # provider (assume_model_exists would otherwise let it through).
  provider = AiModelConstants.provider_for(model)
  raise ArgumentError, "Unsupported AI model for listing optimization: #{model}" if provider.nil?

  chat = RubyLLM.chat(model: model, provider: provider, assume_model_exists: true)
  # Claude Opus 4.7+ (the default listing model is claude-opus-4-8) rejects
  # temperature/top_p/top_k with a 400 — only set it for models that accept it.
  chat.with_temperature(0.7) unless AiModelConstants.rejects_sampling_params?(model)

  # 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 via cacheable_prompt() for Anthropic prefix caching
  # so consecutive item optimizations reuse the cached prefix (the default is a
  # Claude model). Non-Anthropic selections receive plain text. Per-item dynamic
  # messages are always 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.pluck(:content).join("\n")
  response = RubyLLM::Instrumentation.with(feature: 'amazon_listing') do
    chat.ask(user_content)
  end

  result = {
    parameters: {
      model: model,
      messages: messages
    },
    target_keywords: @target_keywords,
    response: parse_response(response)
  }
  # Record temperature only when it was actually sent — Opus 4.7+ rejects it, so
  # the request above omits it; claiming 0.7 in the metadata would be misleading.
  result[:parameters][:temperature] = 0.7 unless AiModelConstants.rejects_sampling_params?(model)

  # 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



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'app/services/amazon/listing_optimizer.rb', line 243

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



357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'app/services/amazon/listing_optimizer.rb', line 357

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



344
345
346
347
348
349
350
351
352
353
354
355
# File 'app/services/amazon/listing_optimizer.rb', line 344

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



267
268
269
270
271
272
273
# File 'app/services/amazon/listing_optimizer.rb', line 267

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