Skip to content
RailsDev.io

How to Embed Real‑Time AI Market Research into Your Rails SaaS

Learn to integrate the open‑source ‘last30days‑skill’ into a Rails app, automatically pulling and summarizing market trends from Reddit, X, YouTube and more for

Diagram: Crawler Service → AI Skill Engine → Rails Dashboard
On this page
  1. Why “AI market research Rails” Is More Than a Buzz Phrase
  2. Architectural Overview
  3. Building the Crawler Service
  4. Defining the AI Skill
  5. Orchestrating with a Background Job
  6. Rendering the Insights in the Dashboard
  7. Testing the End‑to‑End Flow
  8. Operational Considerations
  9. When to Pull Back: Knowing the Limits
  10. Extending the Pattern: From Insights to Action
  11. TL;DR Checklist for Adding AI‑Driven Market Research
  12. Frequently asked questions
  13. Conclusion

I’ve been building Rails SaaS products for over a decade, and AI market research Rails workflows let teams pull competitor pricing, release updates, and public sentiment directly into their Rails dashboard instead of doing manual tab-hopping. Using an open‑source skill pattern such as last30days-skill behind Active Job and Turbo Streams, you can keep research summaries beside your own product metrics without spinning up a separate microservice.


Why “AI market research Rails” Is More Than a Buzz Phrase

The pain points we’re solving

  • Data latency – Traditional market‑research tools (Crunchbase, SimilarWeb, etc.) update on a weekly or monthly cadence. By the time you see a new pricing tier, your competitors have already captured early adopters.
  • Context switching – Your product team spends hours opening tabs, copying charts, and pasting notes into Notion. That friction kills velocity.
  • Signal‑to‑noise – Raw data (tweets, blog posts, release notes) is noisy. Humans are great at pattern‑recognition, but they’re also prone to confirmation bias.

An AI market research pipeline can address all three: it pulls fresh data, processes it in the background, and returns a concise, structured summary that lives next to your own metrics. The key is to keep the whole thing inside Rails, so you don’t have to maintain a separate micro‑service stack.

Open‑source LLMs vs. closed APIs

I’ve experimented with both OpenAI’s ChatGPT and the open‑source Llama 2 models hosted on a modest GPU instance. The open‑source route gives you full control over prompts, costs, and data residency, which is often a compliance requirement for SaaS handling sensitive user data. The trade‑off is a slightly higher engineering overhead to spin up the inference server.

Verification note
I have not measured the exact cost difference between OpenAI’s API and a self‑hosted Llama 2 instance for this specific workload. The statement reflects typical observations but should be validated against your own pricing and infrastructure.


Architectural Overview

Below is the high‑level diagram of the components we’ll assemble:

  1. Crawler Service – A lightweight Ruby class that fetches HTML or JSON from target URLs (e.g., competitor pricing pages, product blogs, Twitter API).
  2. LLM Skill – An open‑source skill that receives raw text and returns a structured summary (key features, price changes, sentiment).
  3. Background Job – A Rails ActiveJob that orchestrates the crawl, invokes the LLM, and persists the result.
  4. Dashboard UI – A simple view that renders the latest insights, refreshed on a schedule or on demand.

All of this lives in a single Rails codebase, leveraging Active Job, Sidekiq (or any other queue), and Hotwire for real‑time updates. If you already have an AI‑agent framework in place, you can plug the skill into it; see my post on Agent Skills for Rails for more details.


Building the Crawler Service

Choosing a HTTP client

Rails ships with Net::HTTP, but I prefer HTTParty for its declarative syntax and built‑in timeout handling. Install it:

bash
bundle add httparty

A reusable crawler class

ruby
# app/services/market_research/crawler.rb
module MarketResearch
  class Crawler
    include HTTParty
    default_timeout 10

    # Accepts an array of URLs and returns a hash of raw HTML strings
    def fetch(urls)
      urls.each_with_object({}) do |url, results|
        begin
          response = self.class.get(url, headers: default_headers)
          results[url] = response.body if response.success?
        rescue Net::OpenTimeout, Net::ReadTimeout => e
          Rails.logger.warn "Timeout fetching #{url}: #{e.message}"
          results[url] = nil
        rescue StandardError => e
          Rails.logger.error "Error fetching #{url}: #{e.message}"
          results[url] = nil
        end
      end
    end

    private

    def default_headers
      {
        "User-Agent" => "RailsSaaSMarketResearch/1.0 (+https://yourapp.com)",
        "Accept" => "text/html,application/json"
      }
    end
  end
end

The Crawler is deliberately thin: it only retrieves raw payloads. All parsing (HTML → text, JSON → relevant fields) happens downstream, keeping the service testable and reusable.

Handling rate limits and politeness

If you’re scraping public sites, respect robots.txt and add a small sleep between requests. For APIs (Twitter, Crunchbase), use their official SDKs and honor the rate‑limit headers. The Crawler can be extended with a middleware that checks X‑RateLimit‑Remaining and backs off accordingly.


Defining the AI Skill

What is an “AI skill”?

In the Rails AI ecosystem, a skill is a small, composable unit that takes a well‑defined input and returns a deterministic output. Think of it as a function that lives behind an HTTP endpoint or a local binary. For market research we need a skill that:

  • Accepts a blob of text (raw HTML stripped of tags, or JSON payloads).
  • Extracts features, pricing, release dates, and sentiment.
  • Returns a JSON object with those fields.

Using llama.cpp with a custom prompt

Assuming you have a Llama 2 model running via llama.cpp, you can invoke it with a simple shell command. Here’s a Bash wrapper that the Rails skill will call:

bash
#!/usr/bin/env bash
# bin/llama_market_skill.sh
# Usage: echo "$INPUT_TEXT" | ./bin/llama_market_skill.sh

MODEL_PATH="/opt/llama/models/llama-2-7b-chat.Q4_K_M.gguf"
PROMPT=$(cat <<'EOF'
You are an expert market analyst. Summarize the following raw text into a JSON object with these keys:
- features: array of notable product features
- pricing: any price information found
- release_date: any dates or version numbers
- sentiment: overall sentiment (positive, neutral, negative)
If a field cannot be determined, set its value to null.
Output only valid JSON.
EOF
)

# Read stdin into a variable
INPUT=$(cat)

# Combine prompt and input
FULL_PROMPT="${PROMPT}\n\n${INPUT}"

# Call llama.cpp
/opt/llama/llama-cli \
  --model "$MODEL_PATH" \
  --prompt "$FULL_PROMPT" \
  --temp 0.2 \
  --n-predict 512 \
  --log-disable

Make the script executable (chmod +x bin/llama_market_skill.sh). The script reads raw text from STDIN, prepends a deterministic prompt, and asks the model to produce a JSON blob. The low temperature (0.2) nudges the model toward deterministic output, which is crucial for downstream processing.

Wrapping the skill in Ruby

ruby
# app/services/market_research/llama_skill.rb
module MarketResearch
  class LlamaSkill
    SKILL_PATH = Rails.root.join("bin/llama_market_skill.sh").to_s

    def summarize(text)
      json_output = Open3.capture3("bash", SKILL_PATH, stdin_data: text).first
      JSON.parse(json_output)
    rescue JSON::ParserError => e
      Rails.logger.error "LLM returned malformed JSON: #{e.message}"
      {}
    end
  end
end

The LlamaSkill isolates the external process call, making it easy to stub in tests. You can swap the implementation for an OpenAI client later without touching the rest of the pipeline.


Orchestrating with a Background Job

The job’s responsibilities

  1. Fetch the raw sources using Crawler.
  2. Normalize the payloads (strip HTML tags, flatten JSON).
  3. Summarize each source with LlamaSkill.
  4. Merge the individual summaries into a single market‑insight record.
  5. Persist the result in a MarketInsight model.

The MarketInsight model

ruby
# app/models/market_insight.rb
class MarketInsight < ApplicationRecord
  # columns: source_url:string, raw_text:text, summary:jsonb, fetched_at:datetime
  validates :source_url, presence: true
  validates :summary, presence: true
end

We store the raw text for auditability and the JSON summary for quick rendering.

The job implementation

ruby
# app/jobs/market_research/collect_insights_job.rb
module MarketResearch
  class CollectInsightsJob < ApplicationJob
    queue_as :default
    retry_on StandardError, attempts: 3, wait: :exponential_backoff

    SOURCE_URLS = [
      "https://competitor1.com/pricing",
      "https://competitor2.com/blog",
      "https://api.twitter.com/2/tweets?query=%23competitor1"
    ].freeze

    def perform
      crawler = Crawler.new
      raw_results = crawler.fetch(SOURCE_URLS)

      raw_results.each do |url, body|
        next if body.blank?

        normalized = normalize(body, url)
        summary = LlamaSkill.new.summarize(normalized)

        MarketInsight.create!(
          source_url: url,
          raw_text: normalized,
          summary: summary,
          fetched_at: Time.current
        )
      end
    end

    private

    # Very naive HTML → text conversion; replace with Nokogiri if needed.
    def normalize(content, url)
      if url.end_with?(".json") || content.lstrip.start_with?("{")
        JSON.parse(content).to_s
      else
        ActionView::Base.full_sanitizer.sanitize(content)
      end
    end
  end
end

The job is deliberately simple: it runs the same pipeline for each source, stores each result, and leaves aggregation to the view layer. You can schedule it with cron‑style syntax using the sidekiq‑cron gem or Rails’ built‑in ActiveJob::Base.set(wait_until: ...) for more granular control.


Rendering the Insights in the Dashboard

Hotwire‑driven UI

Assuming you already have a Hotwire‑enabled Rails app, we can create a Turbo Stream that updates the insights panel whenever a new MarketInsight record is created.

erb
<!-- app/views/market_insights/index.html.erb -->
<h2 class="text-xl font-semibold mb-4">Live Market Insights</h2>

<div id="insights">
  <%= render @insights %>
</div>

<%= button_to "Refresh Now", market_research_collect_insights_path, method: :post, class: "btn btn-primary mt-4" %>
erb
<!-- app/views/market_insights/_market_insight.html.erb -->
<div id="<%= dom_id(insight) %>" class="p-4 border rounded mb-2">
  <p class="text-sm text-gray-600"><%= insight.source_url %> – <%= time_ago_in_words(insight.fetched_at) %> ago</p>
  <pre class="bg-gray-100 p-2 rounded"><%= JSON.pretty_generate(insight.summary) %></pre>
</div>

Add a Turbo Stream broadcast in the model:

ruby
# app/models/market_insight.rb
class MarketInsight < ApplicationRecord
  after_create_commit -> { broadcast_append_to "insights" }
end

Now every time the background job finishes, the UI updates automatically—no page reload required.

Summarizing across sources

If you want a single “market snapshot” rather than a list of per‑source blobs, you can add a service that merges the JSON summaries:

ruby
# app/services/market_research/aggregator.rb
module MarketResearch
  class Aggregator
    def self.snapshot
      insights = MarketInsight.order(fetched_at: :desc).limit(10)
      merged = insights.map(&:summary).reduce({}) do |acc, cur|
        acc.deep_merge(cur) { |_key, old_val, new_val| Array(old_val) + Array(new_val) }
      end
      merged.transform_values { |v| v.uniq }
    end
  end
end

Expose it via a controller action and render the result in a separate panel.


Testing the End‑to‑End Flow

Unit tests for the crawler

ruby
# spec/services/market_research/crawler_spec.rb
require "rails_helper"

RSpec.describe MarketResearch::Crawler do
  let(:urls) { ["https://example.com"] }

  before do
    stub_request(:get, "https://example.com")
      .to_return(status: 200, body: "<html><body>Hello</body></html>")
  end

  it "returns raw HTML for each URL" do
    result = described_class.new.fetch(urls)
    expect(result["https://example.com"]).to include("Hello")
  end
end

Integration test for the job

ruby
# spec/jobs/market_research/collect_insights_job_spec.rb
require "rails_helper"

RSpec.describe MarketResearch::CollectInsightsJob, type: :job do
  before do
    allow_any_instance_of(MarketResearch::Crawler).to receive(:fetch).and_return(
      "https://competitor1.com/pricing" => "<html>Price: $49/mo</html>"
    )
    allow_any_instance_of(MarketResearch::LlamaSkill).to receive(:summarize).and_return(
      { "features" => ["Feature A"], "pricing" => "$49/mo", "release_date" => nil, "sentiment" => "neutral" }
    )
  end

  it "creates a MarketInsight record" do
    expect { described_class.perform_now }.to change(MarketInsight, :count).by(1)
  end
end

These tests give you confidence that the pipeline works even when the external LLM or remote sites are unavailable.


Operational Considerations

Scaling the LLM inference

Running a 7‑B parameter model on a single GPU can handle a few requests per minute. If your SaaS serves hundreds of customers, you’ll need to:

  • Batch requests – Collect multiple source texts and send them in a single prompt.
  • Horizontal scale – Deploy multiple inference containers behind a load balancer (e.g., using Docker Compose or Kubernetes).
  • Cache results – Store the LLM output for a given source URL for a configurable TTL (e.g., 6 hours) to avoid redundant calls.

Cost monitoring

Even with an open‑source model, GPU time isn’t free. Track the number of inference calls and the duration of each job. You can instrument the LlamaSkill wrapper with ActiveSupport notifications:

ruby
# app/services/market_research/llama_skill.rb
def summarize(text)
  ActiveSupport::Notifications.instrument("llama_skill.summarize") do
    json_output = Open3.capture3("bash", SKILL_PATH, stdin_data: text).first
    JSON.parse(json_output)
  end
end

Then subscribe in an initializer to push metrics to Prometheus or your preferred observability stack.

Data privacy

Because the skill processes raw competitor content, you should:

  • Strip personally identifiable information (PII) before sending it to the LLM.
  • Run the model on‑premises if your compliance team requires data never to leave your network.
  • Log only hashes of source URLs for audit trails, not the full payload.

When to Pull Back: Knowing the Limits

AI market research is powerful, but it isn’t a silver bullet. Here are scenarios where I’d advise a more manual approach:

Situation Why AI Might Falter
Highly regulated industries (finance, healthcare) Legal constraints on automated data collection and model inference.
Sparse public data LLMs can hallucinate when the source material is thin; you’ll get “best‑guess” summaries that may be misleading.
Rapidly shifting markets (crypto, meme stocks) Real‑time sentiment can change in seconds; a background job that runs every hour may be too stale.

In those cases, treat the AI pipeline as a first‑draft assistant and let a human analyst verify the output before it reaches stakeholders.


Extending the Pattern: From Insights to Action

Once you have structured market data, the next logical step is to close the loop:

  • Feature flag toggles – Automatically enable a beta flag when the LLM detects a competitor launching a new feature.
  • Pricing alerts – Trigger a Slack webhook if the pricing field drops below a threshold you set.
  • Product roadmap enrichment – Feed the aggregated JSON into a planning tool (e.g., Jira, Clubhouse) via their APIs.

Because each piece (crawler, skill, job) is decoupled, you can plug in additional agents without rewriting the core. For a deeper dive on building maintainable AI agents in Rails, see my guide on Ruby on Rails AI Integration.


TL;DR Checklist for Adding AI‑Driven Market Research

  1. Define source URLs (pricing pages, blogs, social‑media APIs).
  2. Add httparty and implement MarketResearch::Crawler.
  3. Set up an LLM inference server (e.g., Llama 2 via llama.cpp).
  4. Write a deterministic prompt and wrap it in MarketResearch::LlamaSkill.
  5. Create MarketInsight model with raw_text and summary columns.
  6. Implement CollectInsightsJob to orchestrate fetch → summarize → persist.
  7. Schedule the job (Sidekiq‑cron, whenever, or manual trigger).
  8. Render results with Hotwire Turbo Streams for instant UI updates.
  9. Add tests for crawler, skill wrapper, and job.
  10. Monitor GPU usage, cache results, and enforce privacy policies.

Frequently asked questions

Should AI market-research scraping run inside web requests?

No. Always run HTTP fetches and LLM summarization inside background jobs (Solid Queue or Sidekiq) with rate limits and timeouts so slow external sites never tie up Puma threads.

How do I prevent the LLM from hallucinating competitor numbers?

Require JSON output that quotes the source URL and snippet verbatim, store the raw scraped text alongside the summary, and treat missing fields as null rather than asking the model to guess.

Can I run this workflow without sending data to OpenAI or Anthropic?

Yes. Point the skill wrapper at a self-hosted Ollama or vLLM endpoint if compliance requires keeping fetched market notes inside your own infrastructure.

Conclusion

Embedding an automated crawler, structured skill, and background job into your Rails app gives product teams timely market intelligence without leaving their own dashboard.

If you want help shipping production AI pipelines inside a Rails SaaS, explore my AI software development services or book a discovery call.

Keep reading