Integrating stitch skills rails patterns lets Rails teams pair reusable skill definitions (such as Google Labs’ stitch-skills and the Agent Skills format) with standard Rails service objects, background jobs, and validation rather than locking AI features into ad-hoc prompts.
In this post I’ll walk through the architectural patterns for integrating skill contracts into a Rails 8.1 app, how to test and instrument them in production, and where a pure Ruby rule still beats an LLM.
Why AI Agents Matter in Modern Rails Apps
Rails gives us convention over configuration, but it still expects us to write the business logic that powers every feature. When you need a conversational UI, a real‑time recommendation engine, or automated content moderation, you either:
- Roll your own LLM wrapper – which quickly becomes a maintenance nightmare, or
- Vendor‑lock into a proprietary SDK – which makes it hard to swap models or comply with data‑privacy policies.
Stitch Skills solves both problems by defining a language‑agnostic contract for “skills” (think of them as micro‑agents) that can be implemented in any LLM provider and invoked from any host language. The contract lives in a tiny JSON schema, and the Ruby gem (stitch-skills) ships a thin client that turns a skill into a plain Ruby object.
Verification note
The exact JSON schema definition for a Stitch Skill is maintained in the official repository; I have not verified the latest schema version against the gem source code.
Because the contract is open, you can mix and match providers (OpenAI, Anthropic, local Ollama instances) without touching your Rails code. That’s the “plug‑and‑play” promise that makes the library attractive for teams that already have CI pipelines, test suites, and a culture of incremental refactoring.
Introducing Stitch Skills: The Open‑Standard Plug‑and‑Play Layer
What is a Stitch Skill?
At its core, a Stitch Skill is a named function that accepts a JSON payload and returns a JSON response. The payload can contain any domain‑specific data you like—user IDs, text snippets, timestamps—while the response must conform to the schema the skill declares. Think of it as a typed RPC that happens to be powered by an LLM under the hood.
The Ruby client abstracts the RPC call behind a simple method:
result = MySkill.call(input: { user_id: 42, query: "What’s my next task?" })If the skill is backed by a remote LLM service, the client marshals the request, sends it over HTTPS, and unmarshals the JSON response. If you run the skill locally (e.g., via a Docker container that hosts a model), the same call works—no code changes required.
The Core Design Goals
| Goal | Why it matters for Rails |
|---|---|
| Interoperability | You can swap the LLM provider without touching the Rails code. |
| Sandboxing | Skills run in isolated containers, reducing the blast radius of a misbehaving model. |
| Versioning | Each skill declares its own version; Rails can negotiate upgrades safely. |
| Observability | The client emits structured logs that integrate with Rails’ ActiveSupport::Notifications. |
These goals line up nicely with the Rails philosophy of convention, testability, and explicit configuration. In practice, you’ll see the benefits when you start treating a skill like any other service object.
Getting Started: Adding Stitch Skills to a Rails Project
Install the gem and configure the client
First, add the gem to your Gemfile. The official gem lives at https://rubygems.org/gems/stitch-skills.
# Gemfile
gem "stitch-skills", "~> 0.3"Run bundle install, then generate an initializer:
$ rails generate stitch:installThe generator creates config/initializers/stitch_skills.rb with a minimal configuration block:
# config/initializers/stitch_skills.rb
StitchSkills.configure do |config|
# Choose your default provider (OpenAI, Anthropic, etc.)
config.provider = :openai
# API credentials are pulled from ENV for security
config.api_key = ENV.fetch("STITCH_SKILLS_API_KEY")
# Optional: custom endpoint for self‑hosted models
# config.endpoint = "http://localhost:11434/v1/chat/completions"
endBecause Rails already loads dotenv-rails in many projects, you can safely store the key in .env.local. The client respects Rails’ secrets.yml conventions, so you could also place the key under Rails.application.credentials.
Defining your first skill
Stitch Skills encourages you to keep the skill definition (the JSON schema and the prompt) separate from the Rails code. The easiest way is to create a skills/ directory at the project root and add a YAML file:
# skills/next_task.yaml
name: next_task
version: "1.0"
description: |
Given a user ID, return the next actionable task from the
user's task queue, formatted as plain text.
input_schema:
type: object
required: [user_id]
properties:
user_id:
type: integer
output_schema:
type: object
required: [task]
properties:
task:
type: string
prompt: |
You are a helpful assistant that knows the internal task
management system of Acme Corp. Given the user ID, fetch the
next pending task from the database and return it as plain text.Once the file exists, register the skill in an initializer:
# config/initializers/stitch_skills.rb (append)
StitchSkills.register_skill_path(Rails.root.join("skills"))The client will read the YAML, validate the schemas, and expose a Ruby class named after the skill (NextTask).
Wiring the skill into a controller or job
You can invoke a skill from any part of the Rails stack. Here’s a typical controller action that surfaces the next task in a JSON API:
# app/controllers/api/v1/tasks_controller.rb
class Api::V1::TasksController < ApplicationController
def next
skill = StitchSkills::NextTask.call(input: { user_id: current_user.id })
render json: { next_task: skill.output["task"] }
rescue StitchSkills::Error => e
Rails.logger.error "Stitch skill failed: #{e.message}"
render json: { error: "Unable to fetch next task" }, status: :service_unavailable
end
endIf you prefer background processing (e.g., enriching a record after creation), you can call the same skill from an ActiveJob:
# app/jobs/enrich_user_profile_job.rb
class EnrichUserProfileJob < ApplicationJob
queue_as :default
def perform(user_id)
skill = StitchSkills::UserProfileEnricher.call(input: { user_id: user_id })
user = User.find(user_id)
user.update!(profile_summary: skill.output["summary"])
end
endBecause the client raises a dedicated StitchSkills::Error hierarchy, you can handle failures consistently across sync and async contexts.
Real‑World Patterns: Where Stitch Skills Shine
Conversational helpers in admin dashboards
Admin panels often need quick, context‑aware answers—think “Why was this order flagged?” or “Summarize this user’s recent activity.” By exposing a skill that receives the record ID and returns a markdown summary, you can drop a single line into a view:
<%# app/views/admin/orders/show.html.erb %>
<h2>AI‑Generated Summary</h2>
<div id="order-summary">
<%= render partial: "shared/ai_summary", locals: { skill: StitchSkills::OrderSummarizer, id: @order.id } %>
</div>The partial calls the skill synchronously (or via Turbo Streams for a non‑blocking UI) and renders the markdown safely with sanitize.
Background data enrichment pipelines
Many SaaS products enrich inbound data (e.g., tagging a support ticket with sentiment). A skill that accepts raw text and returns a set of tags can be chained in a Sidekiq worker:
class TicketTaggingWorker
include Sidekiq::Worker
def perform(ticket_id)
ticket = Ticket.find(ticket_id)
result = StitchSkills::SentimentTagger.call(input: { text: ticket.body })
ticket.update!(sentiment: result.output["sentiment"])
end
endBecause the skill is versioned, you can roll out a new tagging model without redeploying the worker—just bump the skill’s version in the YAML file and reload the initializer.
On‑the‑fly content moderation
User‑generated content is a classic liability. Instead of building a custom moderation pipeline, you can delegate to a moderation skill that returns a boolean flag and a short explanation:
class CommentsController < ApplicationController
def create
comment = current_user.comments.build(comment_params)
moderation = StitchSkills::ContentModerator.call(input: { text: comment.body })
if moderation.output["allowed"]
comment.save!
render json: comment, status: :created
else
render json: { error: moderation.output["reason"] }, status: :forbidden
end
end
endThe skill can be swapped out for a stricter model during a compliance audit, again without touching the controller logic.
Testing and Observability
Unit‑testing a skill with RSpec
Stitch Skills ships a test double that mimics the remote provider. In your spec_helper.rb you can enable it:
# spec/spec_helper.rb
StitchSkills.configure do |config|
config.test_mode = true
endNow write a spec that asserts the skill receives the correct payload and returns the expected shape:
# spec/skills/next_task_spec.rb
require "rails_helper"
RSpec.describe StitchSkills::NextTask do
it "returns the next task for a known user" do
# Stub the remote call
allow(described_class).to receive(:call).and_return(
OpenStruct.new(output: { "task" => "Review quarterly report" })
)
result = described_class.call(input: { user_id: 1 })
expect(result.output["task"]).to eq("Review quarterly report")
end
endBecause the stub lives at the class level, you can test error handling separately:
allow(described_class).to receive(:call).and_raise(StitchSkills::Error::ProviderUnavailable)Monitoring latency and failures
The client emits ActiveSupport::Notifications events named stitch_skills.call. You can subscribe in an initializer to push metrics to Prometheus, Datadog, or your preferred APM:
# config/initializers/stitch_skills_monitoring.rb
ActiveSupport::Notifications.subscribe("stitch_skills.call") do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
Rails.logger.info "[Stitch] #{event.payload[:skill_name]} took #{event.duration.round(2)}ms"
# Example: push to Prometheus
# Prometheus::Client::Histogram.get(:stitch_skill_latency).observe(event.duration, labels: { skill: event.payload[:skill_name] })
endThis hook gives you visibility into the latency distribution of each skill, which is essential when you start chaining multiple skills in a single request.
Verification note
The exact name of the notification event (stitch_skills.call) is based on the current gem implementation; it may change in future releases.
Deployment Considerations
Secrets management
Stitch Skills needs an API key for the LLM provider, and optionally a service account for a self‑hosted model. Treat these as any other credential:
- Rails credentials (
rails credentials:edit) for production. - Environment variables (
STITCH_SKILLS_API_KEY) for containerized deployments. - HashiCorp Vault or AWS Secrets Manager if you already have a secret‑rotation pipeline.
Never hard‑code keys in skills/*.yaml; the client injects them at runtime.
Scaling the skill execution layer
If you point the client at a remote API (e.g., OpenAI), scaling is handled by the provider. However, many teams run local inference containers for data‑privacy or cost reasons. In that case:
- Deploy the model as a Docker service behind a load balancer.
- Set
config.endpointin the initializer to the internal URL. - Use Sidekiq concurrency or Rails 8.1
ActiveJob::Continuationsto parallelize calls when a request needs multiple skills.
Remember that each skill call is a network round‑trip, so you’ll want to batch where possible. The library does not yet provide built‑in batching, so you’ll need to orchestrate it yourself (e.g., by sending a single prompt that asks the model to answer multiple sub‑questions).
Verification note
The library’s current version does not include automatic request batching; this is based on the public API documentation and observed behavior.
Common Pitfalls and How to Avoid Them
Version drift between skill providers
Because each skill declares its own version, you might end up with mixed versions in production if you forget to redeploy after updating a YAML file. A simple safeguard is to add a rake task that validates that every registered skill’s version matches the one stored in the database (or a Redis cache) at boot time.
# lib/tasks/stitch_skills.rake
namespace :stitch_skills do
desc "Validate that all skill versions are up to date"
task validate_versions: :environment do
mismatches = StitchSkills.registered_skills.select do |skill|
skill.version != Rails.cache.read("skill_version:#{skill.name}")
end
if mismatches.any?
abort "Version mismatch for: #{mismatches.map(&:name).join(', ')}"
else
puts "All skill versions are in sync."
end
end
endRun this task as part of your CI pipeline.
Over‑reliance on LLM hallucinations
Stitch Skills does not magically make LLM output trustworthy. You must validate any data that will affect business logic. A common pattern is to have the skill return a structured JSON that you then verify against a schema using dry-validation before persisting.
schema = Dry::Schema.JSON do
required(:task).filled(:string)
end
validated = schema.call(skill.output)
raise "Invalid skill output" unless validated.success?If the validation fails, fall back to a deterministic implementation or surface an error to the user.
When Not to Use Stitch Skills
Not every problem benefits from an LLM. Consider the following signals:
- Deterministic business rules (e.g., tax calculations) – keep them in pure Ruby.
- High‑throughput, low‑latency paths – a remote LLM call adds network overhead that can’t be amortized.
- Regulatory constraints that forbid sending user data to third‑party APIs – unless you host the model yourself and can certify data residency.
In those cases, treat Stitch Skills as an optional augmentation rather than a core dependency.
Future Outlook: The Evolving Ecosystem
Stitch Skills is still a young open‑standard. The community is actively adding features like skill composition (calling one skill from another) and runtime skill discovery (dynamic loading from a service registry). As the spec matures, I expect tighter integration with Rails‑specific tools such as ActiveJob continuations and Turbo Streams, which will let us stream AI‑generated content directly to the browser without a full page reload.
If you’re already experimenting with the AG‑UI protocol for real‑time agent UI components, you’ll find that Stitch Skills and AG‑UI complement each other nicely. The former handles the backend contract, while the latter defines the frontend contract. You can read more about that synergy in the post “Bring AI Agents Into Your Rails UI with the AG‑UI Protocol”.
TL;DR Checklist
- Add the gem (
stitch-skills) and generate the initializer. - Store credentials securely (Rails credentials, ENV, or secret manager).
- Define skills in
skills/*.yamland register the directory. - Invoke skills from controllers, jobs, or service objects using
SkillName.call. - Write unit tests with the built‑in test mode and stub responses.
- Subscribe to
stitch_skills.callnotifications for latency monitoring. - Validate skill output with a schema library (
dry-validation). - Guard against version drift with a CI‑run rake task.
- Avoid using skills for deterministic, latency‑critical, or regulated logic.
By treating AI capabilities as first‑class services—just like a payment gateway or an email provider—you can swap models and prompt versions cleanly while keeping your Rails codebase testable. See also Ruby on Rails AI integration for wiring providers directly with RubyLLM.
Frequently asked questions
What are Stitch Skills used for in a Rails workflow?
Repositories like stitch-skills package reusable instructions and schemas for AI-assisted UI and product workflows; inside Rails, mirroring that contract-first structure separates prompt definitions from controllers and background jobs.
Should LLM skill calls run inside Rails controllers?
Only for short, streaming responses with explicit timeouts. Anything multi-step or slow belongs in an Active Job worker (Solid Queue or Sidekiq) with schema validation and fallback handling.
How do you test AI skill integrations reliably in RSpec?
Stub the HTTP/provider boundary with deterministic fixture responses in unit specs, and run a small golden eval suite in CI when prompts or models change.
Conclusion
Structuring stitch skills rails workflows around explicit input/output schemas, Active Job workers, and RSpec stubs keeps LLM features maintainable as models evolve.
If you’re adding AI features or agent workflows to a Rails product, explore my AI software development services or book a discovery call.


