### Installing the Gem Locally Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Command to install the gem onto your local machine after cloning the repository. This is typically done after setting up dependencies with `bin/setup`. ```bash bundle exec rake install ``` -------------------------------- ### Install RubyLLM Template Gem Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Add the gem to your application's Gemfile and run bundle install. Include ruby_llm-schema if you plan to use schema.rb files. ```ruby gem 'ruby_llm' gem 'ruby_llm-template' gem 'ruby_llm-schema' # Optional for schema.rb support ``` -------------------------------- ### Rails Setup for RubyLLM Template Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Run the Rails generator to set up the template system, creating necessary configuration files and directories. ```bash rails generate ruby_llm_template:install ``` -------------------------------- ### Install RubyLLM Template Gem Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Add the gem to your Gemfile and run bundle install. The ruby_llm-schema gem is optional and only needed if you plan to use schema.rb files. ```ruby gem 'ruby_llm' gem 'ruby_llm-template' gem 'ruby_llm-schema' # Optional – required only if using schema.rb files ``` ```bash bundle install # Rails only: scaffold app/prompts/ and config initializer rails generate ruby_llm_template:install ``` -------------------------------- ### User Prompt Template with Context Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Example of a user prompt template. This file can include variables and conditional logic for dynamic content. ```erb <%# app/prompts/extract_metadata/user.txt.erb %> Please analyze this document: <%= document %> <% if defined?(additional_context) && additional_context %> Additional context: <%= additional_context %> <% end %> <% if defined?(focus_areas) && focus_areas&.any? %> Focus on: <%= focus_areas.join(", ") %> <% end %> ``` -------------------------------- ### Example System Prompt Template Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Defines the system message for a prompt template. This sets the AI's behavior and role. ```erb You are an expert document analyzer. Extract metadata from documents in a structured format. ``` -------------------------------- ### Example User Prompt Template with ERB Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Defines the user message for a prompt template, utilizing ERB for dynamic content insertion. Supports conditional logic for additional context. ```erb Please analyze this document: <%= document %> <% if additional_context %> Additional context: <%= additional_context %> <% end %> ``` -------------------------------- ### Running RSpec Tests Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Command to execute the test suite for the gem. Ensure dependencies are installed via `bin/setup` before running tests. ```bash bundle exec rspec ``` -------------------------------- ### Handle Schema Gem Not Installed Error Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Catch and handle `RubyLLM::Template::Error` when a schema file exists but the `ruby_llm-schema` gem is not installed. Provides guidance on adding the gem. ```ruby begin RubyLLM.chat.with_template(:schema_without_gem).complete rescue RubyLLM::Template::Error => e # schema.rb present but ruby_llm-schema not installed # => "Schema file 'schema_without_gem/schema.rb' found but RubyLLM::Schema gem is not installed. # Add 'gem \"ruby_llm-schema\"' to your Gemfile." end ``` -------------------------------- ### Use Scaffolded Template in Rails Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Immediately use a scaffolded template like 'extract_metadata' after installation by passing necessary parameters. ```ruby # Using the scaffolded template immediately after install result = RubyLLM.chat .with_template(:extract_metadata, document: params[:document_text]) .complete ``` -------------------------------- ### Example Schema Definition with RubyLLM::Schema DSL Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Defines a structured output schema using the RubyLLM::Schema DSL. Supports various data types, descriptions, required fields, and nested objects. ```ruby # Using RubyLLM::Schema DSL for clean, type-safe schemas RubyLLM::Schema.create do string :title, description: "Document title" array :topics, description: "Main topics" do string end string :summary, description: "Brief summary" # Optional fields with validation number :confidence, required: false, minimum: 0, maximum: 1 # Nested objects object :metadata, required: false do string :author string :date, format: "date" end end ``` -------------------------------- ### Rails Generator for Prompts Directory Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Scaffold the prompts directory and example template files using the Rails generator. This sets up the basic structure for using RubyLLM templates in a Rails application. ```bash rails generate ruby_llm_template:install # Creates: # config/initializers/ruby_llm_template.rb # app/prompts/.keep # app/prompts/extract_metadata/system.txt.erb # app/prompts/extract_metadata/user.txt.erb # app/prompts/extract_metadata/schema.rb ``` -------------------------------- ### Schema Definition with Context Variables Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Context variables are accessible within `schema.rb` using `RubyLLM::Schema.create`. This example shows how to use conditional logic and default values based on context variables like `categories`, `max_items`, and `max_tags`. ```ruby # schema.rb – context variables are also available here RubyLLM::Schema.create do string :category, enum: categories if defined?(categories) number :max_results, maximum: (max_items || 10) array :tags, description: "Up to #{max_tags || 5} tags" do string end end ``` -------------------------------- ### ERB Template with Context Variables Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Context variables passed to `with_template` or `render_template` are available as local methods within ERB templates and `schema.rb` via `instance_eval`. This example shows conditional logic and iterating over documents. ```erb <%# app/prompts/notify_user/user.txt.erb %> Hello <%= name %>! <% if urgent %> 🚨 URGENT: Please respond immediately. <% else %> 📋 Standard request – no rush. <% end %> Processing <%= documents.length %> document<%= documents.length == 1 ? "" : "s" %>: <% documents.each_with_index do |doc, i| %> <%= i + 1 %>. <%= doc.title %> (<%= doc.type %>) <% end %> ``` -------------------------------- ### Basic Template Usage with RubyLLM Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Demonstrates how to use a pre-defined template to complete a chat interaction. Ensure the template directory structure and files are correctly set up. ```ruby # app/ # prompts/ # extract_metadata/ # ├── system.txt.erb # System message # ├── user.txt.erb # User prompt # ├── assistant.txt.erb # Assistant message (optional) # └── schema.rb # RubyLLM::Schema definition (optional) chat = RubyLLM.chat chat.with_template(:extract_metadata, document: @document).complete ``` -------------------------------- ### Chaining Multiple Template Calls Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Illustrates how to chain multiple `with_template` calls to build a complex prompt sequence. This is useful for initializing sessions or loading context before asking a question. ```ruby chat = RubyLLM.chat .with_template(:initialize_session, user: current_user) .with_template(:load_context, project: @project) # Add more messages dynamically chat.ask("What should we focus on first?") ``` -------------------------------- ### Schema definition with `RubyLLM::Schema` DSL Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Describes how to define structured output using a `schema.rb` file within a template folder, leveraging the `RubyLLM::Schema` DSL. ```APIDOC ## Schema definition with `RubyLLM::Schema` DSL Place a `schema.rb` file inside a template folder to enforce structured output. The file is evaluated with `instance_eval`, so all context variables passed to `with_template` are accessible. Requires the `ruby_llm-schema` gem; a clear error is raised if the file exists but the gem is absent. ### Usage ```ruby # schema.rb RubyLLM::Schema.create do string :category, enum: categories if defined?(categories) number :max_results, maximum: (max_items || 10) array :tags, description: "Up to #{max_tags || 5} tags" do string end end ``` ``` -------------------------------- ### Apply Template to Chat Instance Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Use `with_template` to load and render template files, add messages to the chat, and apply a schema. Returns `self` for chaining. Raises `RubyLLM::Template::Error` if the template folder is missing or empty. ```ruby result = RubyLLM.chat .with_template(:extract_metadata, document: @document) .complete ``` ```ruby result = RubyLLM.chat .with_template(:extract_metadata, document: @document, additional_context: "Focus on financial metrics", focus_areas: ["revenue", "challenges", "projections"] ) .complete ``` ```ruby chat = RubyLLM.chat .with_template(:initialize_session, user: current_user) .with_template(:load_context, project: @project) response = chat.ask("What should we focus on first?") ``` ```ruby begin RubyLLM.chat.with_template(:nonexistent).complete rescue RubyLLM::Template::Error => e puts e.message # => "Template 'nonexistent' not found in /your/app/prompts" end ``` -------------------------------- ### Error Handling for Template Not Found Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Demonstrates how to rescue `RubyLLM::Template::Error` to gracefully handle cases where a template or its associated schema file is not found, or if the `RubyLLM::Schema` gem is missing. ```ruby begin RubyLLM.chat.with_template(:extract_metadata).complete rescue RubyLLM::Template::Error => e puts e.message # "Template 'extract_metadata' not found in /path/to/prompts" # "Schema file 'extract_metadata/schema.rb' found but RubyLLM::Schema gem is not installed" end ``` -------------------------------- ### Reset Configuration to Defaults Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Discard the current configuration singleton to revert to default settings. This is primarily useful in test suites to ensure a clean state. ```ruby RSpec.configure do |config| config.before(:each) do RubyLLM::Template.reset_configuration! end end # After reset, the directory reverts to the default RubyLLM::Template.configuration.template_directory # => "/your/app/prompts" (Rails) or "./prompts" (plain Ruby) ``` -------------------------------- ### Configure Template Directory Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Set the global directory for prompt templates. The default varies between Rails applications and plain Ruby applications. This configuration should be done once during application boot. ```ruby # config/initializers/ruby_llm_template.rb (Rails) RubyLLM::Template.configure do |config| config.template_directory = Rails.root.join("app", "prompts") # Or a custom path: # config.template_directory = Rails.root.join("app", "ai_prompts") end # Plain Ruby application RubyLLM::Template.configure do |config| config.template_directory = File.expand_path("prompts", __dir__) end # Read back the active directory at any time puts RubyLLM::Template.configuration.template_directory # => "/your/app/prompts" ``` -------------------------------- ### Complete Chat Interaction with Template and Context Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Executes a chat completion using a template, passing context variables. This shows how the gem renders templates and applies them to the chat instance. ```ruby chat = RubyLLM.chat chat.with_template(:extract_metadata, document: @document, additional_context: "Focus on technical details").complete # Under the hood, RubyLLM::Template renders the templates with the context variables # and applies them to the chat instance using native RubyLLM methods: # chat.add_message(:system, rendered_system_message) # chat.add_message(:user, rendered_user_message) # chat.add_schema(instantiated_schema) ``` -------------------------------- ### Complex Template with Conditional Logic and Loops Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Demonstrates a template that uses conditional logic (`include_charts`) and loops (`reports.each`) to dynamically generate content. Ensure `reports` and `deadline` are properly defined in the context. ```ruby # Template with conditional logic and loops RubyLLM.chat.with_template(:analyze_reports, reports: @reports, priority: "high", include_charts: true, deadline: 1.week.from_now ).complete ``` -------------------------------- ### Low-Level Template Access with Loader Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Use `RubyLLM::Template::Loader` for fine-grained control over template access, such as inspecting roles, rendering individual files, or loading schema objects without a chat instance. Initialize with a template name or explicit directory. ```ruby loader = RubyLLM::Template::Loader.new(:extract_metadata) # Or with an explicit directory: loader = RubyLLM::Template::Loader.new(:extract_metadata, template_directory: "/path/to/prompts") ``` ```ruby loader.template_exists? # => true / false ``` ```ruby loader.available_roles # => ["system", "user", "schema"] ``` ```ruby system_text = loader.render_template("system") # => "You are an expert document analyzer..." ``` ```ruby user_text = loader.render_template("user", document: "Q3 report...", focus_areas: ["revenue"]) # => "Please analyze this document: Q3 report...\nFocus on: revenue" ``` ```ruby schema = loader.load_schema_class(input: "test document", max_tags: 5) schema.to_json_schema # => { name: "ExtractMetadataSchema", # schema: { type: "object", properties: { title: {...}, ... }, required: [...] } } ``` ```ruby schema_instance = loader.render_template("schema", document: @doc) ``` -------------------------------- ### chat.with_template(name, **context) Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Applies a named template to a chat instance, rendering messages and applying schema. Returns self for chaining. Raises RubyLLM::Template::Error on failure. ```APIDOC ## `chat.with_template(name, **context)` — Apply a template to a chat instance The primary API. Loads and renders all files found in the named template folder, adds each rendered message to the chat in order (system → user → assistant), and applies the schema if present. Returns `self` for chaining. Raises `RubyLLM::Template::Error` if the template folder does not exist or is empty. ### Usage Examples ```ruby # Basic usage – complete in one chain result = RubyLLM.chat .with_template(:extract_metadata, document: @document) .complete # Passing multiple context variables (available in both ERB and schema.rb) result = RubyLLM.chat .with_template(:extract_metadata, document: @document, additional_context: "Focus on financial metrics", focus_areas: ["revenue", "challenges", "projections"] ) .complete # Chaining multiple templates before asking a follow-up question chat = RubyLLM.chat .with_template(:initialize_session, user: current_user) .with_template(:load_context, project: @project) response = chat.ask("What should we focus on first?") # Error handling begin RubyLLM.chat.with_template(:nonexistent).complete rescue RubyLLM::Template::Error => e puts e.message # => "Template 'nonexistent' not found in /your/app/prompts" end ``` ``` -------------------------------- ### Usage of Schema with Chat Completion Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Apply a defined schema to a chat template for structured output. Includes error handling for missing schema gems. ```ruby # Usage – schema is applied to the chat automatically result = RubyLLM.chat .with_template(:analyze_results, document: @document, categories: ["finance", "technology", "legal"] ) .complete # Error when gem is missing begin RubyLLM.chat.with_template(:analyze_results).complete rescue RubyLLM::Template::Error => e puts e.message # => "Schema file 'analyze_results/schema.rb' found but RubyLLM::Schema gem is not installed. # Add 'gem \"ruby_llm-schema\"' to your Gemfile." end ``` -------------------------------- ### RubyLLM::Template::Loader Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Provides low-level access to template loading, allowing inspection of roles, rendering individual files, and loading schema objects. ```APIDOC ## `RubyLLM::Template::Loader` — Low-level template access The `Loader` class can be used directly when you need fine-grained control: inspecting available roles, rendering individual role files, or loading schema objects without going through a chat instance. ### Initialization ```ruby loader = RubyLLM::Template::Loader.new(:extract_metadata) # Or with an explicit directory: loader = RubyLLM::Template::Loader.new(:extract_metadata, template_directory: "/path/to/prompts") ``` ### Methods - `template_exists?` - Check whether the template folder exists and has at least one file. Returns `true` or `false`. - `available_roles` - List roles present in the folder. Returns an array of strings (e.g., `["system", "user", "schema"]`). - `render_template(role_name, **context)` - Render a single ERB file with context. Accepts role name and context variables. - `load_schema_class(**context)` - Load the `RubyLLM::Schema` instance defined in `schema.rb`. Returns the schema instance. ### Usage Examples ```ruby loader = RubyLLM::Template::Loader.new(:extract_metadata) # Check existence loader.template_exists? # => true / false # List roles loader.available_roles # => ["system", "user", "schema"] # Render a single ERB file with context system_text = loader.render_template("system") # => "You are an expert document analyzer..." user_text = loader.render_template("user", document: "Q3 report...", focus_areas: ["revenue"]) # => "Please analyze this document: Q3 report...\nFocus on: revenue" # Load the RubyLLM::Schema instance defined in schema.rb schema = loader.load_schema_class(input: "test document", max_tags: 5) schema.to_json_schema # => { name: "ExtractMetadataSchema", # schema: { type: "object", properties: { title: {...}, ... }, required: [...] } } # Render the schema role (same as load_schema_class, returns schema instance) schema_instance = loader.render_template("schema", document: @doc) ``` ``` -------------------------------- ### Structured Output Schema Definition Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Defines the expected structure for the AI's output using the RubyLLM::Schema DSL. This requires the 'ruby_llm-schema' gem. ```ruby # app/prompts/extract_metadata/schema.rb RubyLLM::Schema.create do string :title, description: "Document title" string :summary, description: "Brief summary" array :topics, description: "Main topics" do string end number :confidence, required: false, minimum: 0, maximum: 1 object :metadata, required: false do string :author string :date, format: "date" end end ``` -------------------------------- ### Defining JSON Schemas with Ruby DSL Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Shows how to define JSON schemas using RubyLLM::Schema, a Ruby DSL that replaces traditional JSON schema files. This approach offers type safety, dynamic schema generation, and improved readability. ```ruby # app/prompts/analyze_results/schema.rb RubyLLM::Schema.create do number :confidence, minimum: 0, maximum: 1, description: "Analysis confidence" array :results, description: "Analysis results" do object do string :item, description: "Result item" number :score, minimum: 0, maximum: 100, description: "Item score" # Context variables are available string :category, enum: categories if defined?(categories) end end # Optional nested structures object :metadata, required: false do string :model_version string :timestamp, format: "date-time" end end ``` -------------------------------- ### Configure Template Directory in Rails Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Configure the template directory for RubyLLM within a Rails application's initializer. This allows overriding the default 'app/prompts' location. ```ruby # config/initializers/ruby_llm_template.rb (generated) RubyLLM::Template.configure do |config| # Uncomment to override the default app/prompts directory: # config.template_directory = Rails.root.join("app", "ai_prompts") end ``` -------------------------------- ### Configure Template Directory for Non-Rails Apps Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Customize the directory where prompt templates are located for applications not using Rails. This is done via the RubyLLM::Template.configure block. ```ruby RubyLLM::Template.configure do |config| config.template_directory = "/path/to/your/prompts" end ``` -------------------------------- ### Handle Missing Template Error Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Catch and handle `RubyLLM::Template::Error` when a specified template is not found. This is crucial for robust application behavior. ```ruby begin RubyLLM.chat.with_template(:missing_template).complete rescue RubyLLM::Template::Error => e # Template folder not found # => "Template 'missing_template' not found in /your/app/prompts" end ``` -------------------------------- ### ERB context variables Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Explains how context variables passed to `with_template` or `render_template` are made available within ERB templates and `schema.rb`. ```APIDOC ## ERB context variables — Using Ruby logic in templates Every key-value pair passed to `with_template` (or `render_template`) is available as a local method inside the ERB template and inside `schema.rb` via `instance_eval`. ### ERB Template Example ```erb <%# app/prompts/notify_user/user.txt.erb %> Hello <%= name %>! <% if urgent %> 🚨 URGENT: Please respond immediately. <% else %> 📋 Standard request – no rush. <% end %> Processing <%= documents.length %> document<%= documents.length == 1 ? "" : "s" %>: <% documents.each_with_index do |doc, i| %> <%= i + 1 %>. <%= doc.title %> (<%= doc.type %>) <% end %> ``` ### Ruby Usage Example ```ruby RubyLLM.chat.with_template(:notify_user, name: "Alice", urgent: true, documents: [ OpenStruct.new(title: "Q3 Report", type: "financial"), OpenStruct.new(title: "Risk Assessment", type: "compliance") ] ).complete ``` ### `schema.rb` Usage Example ```ruby # schema.rb – context variables are also available here RubyLLM::Schema.create do string :category, enum: categories if defined?(categories) number :max_results, maximum: (max_items || 10) array :tags, description: "Up to #{max_tags || 5} tags" do string end end ``` ``` -------------------------------- ### Override Template Directory in Rails Apps Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md While the gem defaults to `Rails.root.join("app", "prompts")`, you can override this path in the initializer file for custom configurations. ```ruby RubyLLM::Template.configure do |config| config.template_directory = Rails.root.join("app", "ai_prompts") end ``` -------------------------------- ### Passing Context to ERB Template Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt This Ruby code demonstrates how to pass context variables to an ERB template, including strings, booleans, and arrays of objects. ```ruby RubyLLM.chat.with_template(:notify_user, name: "Alice", urgent: true, documents: [ OpenStruct.new(title: "Q3 Report", type: "financial"), OpenStruct.new(title: "Risk Assessment", type: "compliance") ] ).complete ``` -------------------------------- ### Define Schema for Structured Data Extraction Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Define a schema for structured data extraction using RubyLLM::Schema. This schema is automatically applied to the chat completion. ```ruby RubyLLM::Schema.create do # Scalar fields string :document_type, description: "Type of document (report, article, email)" number :confidence, minimum: 0, maximum: 1, description: "Analysis confidence score" # Array of primitives array :key_topics, description: "Main topics discussed" do string end # Array of objects array :entities, required: false, description: "Named entities" do object do string :name string :type, enum: ["person", "organization", "location", "other"] end end # Nested object object :metadata, required: false do string :author string :date, format: "date" string :language end # Dynamic schema based on runtime context variables array :important_dates, required: false, description: "Significant dates" do string format: "date" end end ``` -------------------------------- ### Handle ERB Rendering Failure Source: https://context7.com/danielfriis/ruby_llm-template/llms.txt Catch and handle `RubyLLM::Template::Error` during ERB template rendering, which can occur due to undefined variables or syntax issues. ```ruby begin loader = RubyLLM::Template::Loader.new(:broken) loader.render_template("user", name: undefined_var) rescue RubyLLM::Template::Error => e # ERB rendering failure # => "Failed to render template 'broken/user.txt.erb': undefined local variable..." end ``` -------------------------------- ### Using ERB Context in Templates Source: https://github.com/danielfriis/ruby_llm-template/blob/main/README.md Pass context variables to `with_template` for use within ERB templates. Variables like `name`, `urgent`, `message`, and `documents` are accessible. ```ruby chat = RubyLLM.chat chat.with_template(:message, name: "Alice", urgent: true, documents: @documents) ``` ```erb Hello <%= name %>! <% if urgent %> 🚨 URGENT: <%= message %> <% else %> 📋 Regular: <%= message %> <% end %> Processing <%= documents.length %> documents: <% documents.each_with_index do |doc, i| %> <%= i + 1 %>. <%= doc.title %> <% end %> ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.