### Sublayer Development Setup and Testing Commands Source: https://github.com/sublayerapp/sublayer/blob/main/CLAUDE.md Lists essential Bash commands for setting up and managing the Sublayer project. This includes installing dependencies, running the RSpec test suite, building the gem package, and releasing it to RubyGems. ```bash # Setup bin/setup bundle install # Testing rake spec rake # Building and releasing rake build rake install rake release ``` -------------------------------- ### Logging Configuration Examples Source: https://context7.com/sublayerapp/sublayer/llms.txt Shows how to configure the logger for Sublayer. It demonstrates setting the logger to DebugLogger for console output and JsonLogger for file-based JSON logging. ```ruby # Debug logging to console Sublayer.configuration.logger = Sublayer::Logging::DebugLogger.new # JSON logging to file Sublayer.configuration.logger = Sublayer::Logging::JsonLogger.new("./logs/sublayer.log") ``` -------------------------------- ### Workflow Example with Actions and Generators Source: https://context7.com/sublayerapp/sublayer/llms.txt Illustrates a workflow combining FetchUrlAction, SummaryGenerator, and WriteFileAction. It fetches data from a URL, generates a summary from the fetched content, and then writes the summary to a file. ```ruby # Usage in a workflow url_content = FetchUrlAction.new(url: "https://example.com/api/data").call summary = SummaryGenerator.new(content: url_content).generate WriteFileAction.new(file_path: "./summary.txt", file_contents: summary).call ``` -------------------------------- ### Generate Code from Description using Sublayer Generator (Ruby) Source: https://context7.com/sublayerapp/sublayer/llms.txt This example shows how to create a custom Sublayer Generator to produce code based on a given description and technologies. It defines an output adapter for a single string and a prompt to guide the AI. The usage demonstrates instantiating the generator and calling the `generate` method. ```ruby class CodeFromDescriptionGenerator < Sublayer::Generators::Base llm_output_adapter type: :single_string, name: "generated_code", description: "The generated code in the requested language" def initialize(description:, technologies:) @description = description @technologies = technologies end def generate super end def prompt <<-PROMPT You are an expert programmer in #{@technologies.join(", ")}. You are tasked with writing code using the following technologies: #{@technologies.join(", ")}. The description of the task is #{@description} Take a deep breath and think step by step before you start coding. PROMPT end end # Usage generator = CodeFromDescriptionGenerator.new( description: "A function that calculates fibonacci numbers recursively", technologies: ["Ruby"] ) result = generator.generate puts result # => "def fibonacci(n)\n return n if n <= 1\n fibonacci(n - 1) + fibonacci(n - 2)\nend" ``` -------------------------------- ### Sublayer CLI Commands for Project Scaffolding Source: https://context7.com/sublayerapp/sublayer/llms.txt These bash commands demonstrate how to use the Sublayer CLI to install the gem, create new projects with different templates (CLI, GitHubAction, QuickScript) and AI providers (OpenAI, Claude, Gemini), and generate boilerplate code for custom components like generators, agents, and actions. ```bash # Install the gem gem install sublayer # Create a new CLI application project sublayer new my_app --template=CLI --provider=OpenAI # Create a new GitHub Action project sublayer new my_action --template=GithubAction --provider=Claude # Create a quick script project sublayer new my_script --template=QuickScript --provider=Gemini # Generate a new generator class sublayer generate:generator # Generate a new agent class sublayer generate:agent # Generate a new action class sublayer generate:action ``` -------------------------------- ### Configure OpenAI AI Provider Source: https://github.com/sublayerapp/sublayer/blob/main/README.md Configure Sublayer to use the OpenAI AI provider. Ensure the OPENAI_API_KEY environment variable is set. This example sets the provider and model. ```ruby Sublayer.configuration.ai_provider = Sublayer::Providers::OpenAI Sublayer.configuration.ai_model = "gpt-4o" ``` -------------------------------- ### Generate List of Strings with Ruby Source: https://context7.com/sublayerapp/sublayer/llms.txt The `list_of_strings` adapter returns an array of strings from an AI model. It's useful for generating lists, suggestions, keywords, or multiple items. This example shows how to use it for generating blog post keyword suggestions. ```ruby class BlogPostKeywordSuggestionGenerator < Sublayer::Generators::Base llm_output_adapter type: :list_of_strings, name: "suggestions", description: "List of keyword suggestions" def initialize(topic:, num_keywords: 5) @topic = topic @num_keywords = num_keywords end def generate super end def prompt <<-PROMPT You are an SEO expert tasked with suggesting keywords for a blog post. The blog post topic is: #{@topic} Please suggest relevant #{@num_keywords} keywords or key phrases for this post's topic. Each keyword or phrase should be concise and directly related to the topic. Provide your suggestions as a list of strings. PROMPT end end # Usage generator = BlogPostKeywordSuggestionGenerator.new( topic: "Ruby on Rails performance optimization", num_keywords: 5 ) keywords = generator.generate puts keywords.inspect # => ["rails caching", "database indexing", "N+1 queries", "background jobs", "memory optimization"] ``` -------------------------------- ### Sublayer CLI Generation Commands Source: https://github.com/sublayerapp/sublayer/blob/main/CLAUDE.md Provides examples of Sublayer CLI commands for generating core components of an AI application. These commands help scaffold new Generator, Agent, and Action classes within a Sublayer project. ```bash sublayer generate:generator sublayer generate:agent sublayer generate:action ``` -------------------------------- ### Configure Claude AI Provider Source: https://github.com/sublayerapp/sublayer/blob/main/README.md Configure Sublayer to use the Claude AI provider. Ensure the ANTHROPIC_API_KEY environment variable is set. This example sets the provider and model. ```ruby Sublayer.configuration.ai_provider = Sublayer::Providers::Claude Sublayer.configuration.ai_model ="claude-3-5-sonnet-20240620" ``` -------------------------------- ### Select String from List with Ruby Source: https://context7.com/sublayerapp/sublayer/llms.txt The `string_selection_from_list` adapter returns a single string chosen from a predefined list of options. This is useful for tasks like classification, sentiment analysis, or generating categorical outputs. The example shows sentiment analysis from text. ```ruby class SentimentFromTextGenerator < Sublayer::Generators::Base llm_output_adapter type: :string_selection_from_list, name: "sentiment_value", description: "A sentiment value from the list", options: -> { @sentiment_options } def initialize(text:, sentiment_options:) @text = text @sentiment_options = sentiment_options end def generate super end def prompt <<-PROMPT You are an expert at determining sentiment from text. You are tasked with analyzing the following text and determining its sentiment value. The text is: #{@text} PROMPT end end # Usage generator = SentimentFromTextGenerator.new( text: "I absolutely love this product! It exceeded all my expectations.", sentiment_options: ["positive", "negative", "neutral"] ) sentiment = generator.generate puts sentiment # => "positive" ``` -------------------------------- ### Configure AI Provider in Ruby Source: https://github.com/sublayerapp/sublayer/blob/main/CLAUDE.md Demonstrates how to configure the Sublayer framework to use a specific AI provider and model. This involves setting the `ai_provider` and `ai_model` attributes on the Sublayer configuration object. Ensure the chosen provider and model are compatible with your setup. ```ruby Sublayer.configuration.ai_provider = Sublayer::Providers::Claude Sublayer.configuration.ai_model = "claude-3-5-sonnet-20240620" ``` -------------------------------- ### Generate Single Integer with Ruby Source: https://context7.com/sublayerapp/sublayer/llms.txt The `single_integer` adapter returns a single integer value from an AI model. It is suitable for scoring, rating, counting, or performing numerical analysis. This example demonstrates scoring text complexity. ```ruby class TextComplexityScorer < Sublayer::Generators::Base llm_output_adapter type: :single_integer, name: "complexity_score", description: "A complexity score from 1-10 where 1 is simple and 10 is highly complex" def initialize(text:) @text = text end def generate super end def prompt <<-PROMPT Analyze the following text and rate its complexity on a scale of 1-10: - 1-3: Simple, everyday language - 4-6: Moderate complexity, some technical terms - 7-10: Highly complex, specialized vocabulary Text: #{@text} PROMPT end end ``` -------------------------------- ### Generate Description from Code using Sublayer Generator (Ruby) Source: https://context7.com/sublayerapp/sublayer/llms.txt This snippet illustrates creating a Sublayer Generator to describe a given piece of code. It utilizes the `single_string` output adapter and a prompt designed to elicit a high-level explanation of the code's purpose and functionality. The example shows how to use this generator with a sample Ruby code snippet. ```ruby class DescriptionFromCodeGenerator < Sublayer::Generators::Base llm_output_adapter type: :single_string, name: "code_description", description: "A description of what the code does, its purpose, functionality, and any noteworthy details" def initialize(code:) @code = code end def generate super end def prompt <<-PROMPT You are an experienced software engineer. Below is a chunk of code: #{@code} Please read the code carefully and provide a high-level description of what this code does, including its purpose, functionalities, and any noteworthy details. PROMPT end end # Usage code = <<~RUBY def quicksort(arr) return arr if arr.length <= 1 pivot = arr[arr.length / 2] left = arr.select { |x| x < pivot } middle = arr.select { |x| x == pivot } right = arr.select { |x| x > pivot } quicksort(left) + middle + quicksort(right) end RUBY generator = DescriptionFromCodeGenerator.new(code: code) description = generator.generate puts description # => "This code implements the quicksort algorithm in Ruby..." ``` -------------------------------- ### Text Complexity Scorer Usage Source: https://context7.com/sublayerapp/sublayer/llms.txt Demonstrates how to use the TextComplexityScorer to generate a complexity score for a given text. It initializes the scorer with text and then calls the generate method to get the score. ```ruby generator = TextComplexityScorer.new( text: "Quantum entanglement demonstrates non-local correlations between particles." ) score = generator.generate puts score # => 8 ``` -------------------------------- ### Pin Sublayer Version in Gemfile Source: https://github.com/sublayerapp/sublayer/blob/main/README.md To maintain stability, pin the Sublayer gem version in your Gemfile to a specific minor version. This example shows how to pin to version 0.2.x. ```ruby gem 'sublayer', '~> 0.2' ``` -------------------------------- ### Generate Named Strings Object with Ruby Source: https://context7.com/sublayerapp/sublayer/llms.txt The `named_strings` adapter returns a structured object with multiple named string attributes. It is ideal for generating complex outputs with multiple related fields. This example demonstrates generating a product description with various attributes. ```ruby class ProductDescriptionGenerator < Sublayer::Generators::Base llm_output_adapter type: :named_strings, name: "product_description", description: "Generate product descriptions", attributes: [ { name: "short_description", description: "A brief one-sentence description of the product" }, { name: "long_description", description: "A detailed paragraph describing the product" }, { name: "key_features", description: "A comma-separated list of key product features" }, { name: "target_audience", description: "A brief description of the target audience for this product" } ] def initialize(product_name:, product_category:) @product_name = product_name @product_category = product_category end def generate super end def prompt <<-PROMPT You are a skilled product copywriter. Create compelling product descriptions for the following: Product Name: #{@product_name} Product Category: #{@product_category} Please provide the following: 1. A brief one-sentence description of the product 2. A detailed paragraph describing the product 3. A comma-separated list of key product features 4. A brief description of the target audience for this product PROMPT end end # Usage generator = ProductDescriptionGenerator.new( product_name: "AirPods Pro", product_category: "Wireless Earbuds" ) result = generator.generate puts result.short_description # => "Premium wireless earbuds with active noise cancellation and spatial audio." puts result.long_description # => "The AirPods Pro deliver an immersive listening experience..." puts result.key_features # => "Active Noise Cancellation, Transparency Mode, Spatial Audio, Sweat Resistant" puts result.target_audience # => "Music enthusiasts and professionals seeking premium audio quality..." ``` -------------------------------- ### FetchUrlAction Implementation Source: https://context7.com/sublayerapp/sublayer/llms.txt Implements the FetchUrlAction, a subclass of Sublayer::Actions::Base, for fetching content from a given URL. It uses Ruby's Net::HTTP library to perform the GET request and return the response body. ```ruby class FetchUrlAction < Sublayer::Actions::Base def initialize(url:) @url = url end def call require 'net/http' uri = URI(@url) Net::HTTP.get(uri) end end ``` -------------------------------- ### Sublayer CLI Project Generation Commands Source: https://github.com/sublayerapp/sublayer/blob/main/CLAUDE.md Illustrates commands for generating new projects using the Sublayer CLI. Users can specify the project name, template type (CLI, GithubAction, QuickScript), and the AI provider to be used. ```bash sublayer new PROJECT_NAME --template=[CLI|GithubAction|QuickScript] --provider=[OpenAI|Claude|Gemini] ``` -------------------------------- ### Configure AI Provider and Model in Sublayer (Ruby) Source: https://context7.com/sublayerapp/sublayer/llms.txt This snippet demonstrates how to configure the AI provider and model globally for the Sublayer framework. It shows configurations for OpenAI, Claude, and Gemini, including required environment variables. The block syntax for configuration is also illustrated. ```ruby require 'sublayer' # OpenAI Configuration (default) Sublayer.configuration.ai_provider = Sublayer::Providers::OpenAI Sublayer.configuration.ai_model = "gpt-4o" # Requires: ENV["OPENAI_API_KEY"] # Claude Configuration Sublayer.configuration.ai_provider = Sublayer::Providers::Claude Sublayer.configuration.ai_model = "claude-3-5-sonnet-20240620" # Requires: ENV["ANTHROPIC_API_KEY"] # Gemini Configuration (experimental) Sublayer.configuration.ai_provider = Sublayer::Providers::Gemini Sublayer.configuration.ai_model = "gemini-1.5-pro" # Requires: ENV["GEMINI_API_KEY"] # Configure with block syntax Sublayer.configure do |config| config.ai_provider = Sublayer::Providers::Claude config.ai_model = "claude-3-5-sonnet-20240620" config.logger = Sublayer::Logging::DebugLogger.new end ``` -------------------------------- ### Set Environment Variables for AI Providers Source: https://github.com/sublayerapp/sublayer/blob/main/CLAUDE.md Shows the necessary environment variables required to authenticate with different AI providers. These keys are essential for the Sublayer framework to communicate with services like OpenAI, Anthropic (Claude), and Google Gemini. ```bash OPENAI_API_KEY=your_key_here ANTHROPIC_API_KEY=your_key_here GEMINI_API_KEY=your_key_here ``` -------------------------------- ### RunTestCommandAction Implementation Source: https://context7.com/sublayerapp/sublayer/llms.txt Implements the RunTestCommandAction, a subclass of Sublayer::Actions::Base, designed to execute a given test command. It utilizes Open3.capture3 to capture the standard output, standard error, and exit status of the command. ```ruby class RunTestCommandAction < Sublayer::Actions::Base def initialize(test_command:) @test_command = test_command end def call require 'open3' stdout, stderr, status = Open3.capture3(@test_command) [stdout, stderr, status] end end ``` -------------------------------- ### Configure Gemini AI Provider (Unstable) Source: https://github.com/sublayerapp/sublayer/blob/main/README.md Configure Sublayer to use the Gemini AI provider. Note that Gemini's function calling API is in beta and not recommended for production. Ensure the GEMINI_API_KEY environment variable is set. ```ruby Sublayer.configuration.ai_provider = Sublayer::Providers::Gemini Sublayer.configuration.ai_model = "gemini-1.5-pro" ``` -------------------------------- ### DocumentSyncAgent Definition and Usage Source: https://context7.com/sublayerapp/sublayer/llms.txt Defines a DocumentSyncAgent that monitors source files for changes and synchronizes them to HTML files in an output directory. It uses file change triggers and a goal condition to determine when synchronization is complete. ```ruby class DocumentSyncAgent < Sublayer::Agents::Base def initialize(source_files:, output_dir:) @source_files = source_files @output_dir = output_dir @synced = false end # Watch multiple source files for changes trigger_on_files_changed { @source_files } goal_condition { @synced } check_status do @needs_sync = @source_files.any? do |file| source_mtime = File.mtime(file) output_file = File.join(@output_dir, File.basename(file, ".*") + ".html") !File.exist?(output_file) || File.mtime(output_file) < source_mtime end end step do @source_files.each do |file| content = File.read(file) html = MarkdownToHtmlGenerator.new(markdown: content).generate output_path = File.join(@output_dir, File.basename(file, ".*") + ".html") File.write(output_path, html) end @synced = true end end # Usage agent = DocumentSyncAgent.new( source_files: ["./docs/readme.md", "./docs/guide.md"], output_dir: "./public/docs" ) agent.run ``` -------------------------------- ### WriteFileAction Implementation Source: https://context7.com/sublayerapp/sublayer/llms.txt Implements the WriteFileAction, a subclass of Sublayer::Actions::Base, responsible for writing content to a specified file path. It takes the file path and content as initialization parameters and performs the write operation in its call method. ```ruby class WriteFileAction < Sublayer::Actions::Base def initialize(file_path:, file_contents:) @file_path = file_path @file_contents = file_contents end def call File.write(@file_path, @file_contents) end end ``` -------------------------------- ### Implement Custom Logger for Sublayer Source: https://context7.com/sublayerapp/sublayer/llms.txt This snippet shows how to create a custom logger by inheriting from `Sublayer::Logging::Base`. The `log` method can be overridden to send logs to a custom logging service, enriching messages with additional data like service name. This allows for centralized logging and monitoring of Sublayer applications. ```ruby class CustomLogger < Sublayer::Logging::Base def log(level, message, data = {}) # level: :info, :warn, :error # message: description string # data: hash with request_id, response_time, usage tokens, etc. MyLoggingService.send(level, message, data.merge(service: "sublayer")) end end Sublayer.configuration.logger = CustomLogger.new ``` -------------------------------- ### RSpecAgent Definition and Usage Source: https://context7.com/sublayerapp/sublayer/llms.txt Defines an RSpecAgent that monitors implementation and test files, running tests and automatically fixing code when tests fail. It uses file change triggers and a goal condition to stop when tests pass. ```ruby class RSpecAgent < Sublayer::Agents::Base def initialize(implementation_file_path:, test_file_path:) @implementation_file_path = implementation_file_path @test_file_path = test_file_path @tests_passing = false end # Trigger: Activate when either file changes trigger_on_files_changed { [@implementation_file_path, @test_file_path] } # Goal: Stop when tests pass goal_condition { @tests_passing == true } # Check: Run tests and update status check_status do stdout, stderr, status = Sublayer::Actions::RunTestCommandAction.new( test_command: "rspec #{@test_file_path}" ).call @test_output = stdout @tests_passing = (status.exitstatus == 0) end # Step: Generate and apply code fixes step do modified_implementation = Sublayer::Generators::ModifiedImplementationToPassTestsGenerator.new( implementation_file_contents: File.read(@implementation_file_path), test_file_contents: File.read(@test_file_path), test_output: @test_output ).generate Sublayer::Actions::WriteFileAction.new( file_contents: modified_implementation, file_path: @implementation_file_path ).call end end # Usage agent = RSpecAgent.new( implementation_file_path: "./lib/calculator.rb", test_file_path: "./spec/calculator_spec.rb" ) agent.run # Runs continuously, watching files and fixing code until tests pass ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.