Artificial

A comprehensive Ruby gem for prompt engineering and management. Build, optimize, and maintain AI prompts with advanced features like role-based prompting, data separation, multi-format input support, and structured XML output.

Features

  • Multi-format Input Support: String, XML, YAML, JSON, and message arrays
  • Role-based Prompting: Expert role assignment for optimal AI performance
  • Data Separation: Clear separation between instructions and data
  • XML Structure: Structured prompts with proper organization
  • Method Chaining: Fluent API for building complex prompts
  • Validation: Built-in validation for messages and roles
  • Hallucination Prevention: Grounding requirements and source attribution
  • Tool Integration: Support for function calling and external tools
  • Long Context Optimization: Efficient handling of large documents
  • Example Management: Structured examples with input/output pairs

Installation

Install the gem and add to the application's Gemfile by executing:

$ bundle add artificial

If bundler is not being used to manage dependencies, install the gem by executing:

$ gem install artificial

Usage

Basic Usage

require 'artificial'

# Simple prompt creation
prompt = Artificial::Prompt.new("What is Ruby?")
puts prompt.to_s

Role-based Prompting

# Expert role assignment
prompt = Artificial::Prompt.new(
  text: "Explain object-oriented programming",
  system: "You are a Ruby programming expert with 10 years of experience"
)
puts prompt.to_s

Method Chaining

# Fluent API for building complex prompts
prompt = Artificial::Prompt.new("Analyze this code")
  .with_system("You are a senior Ruby developer")
  .with_context(audience: "junior developers", goal: "code review")
  .with_examples({ input: "class MyClass; end", output: "Simple class definition" })
  .with_thinking(enabled: true)
  .with_grounding(require_quotes: true, require_sources: true)

puts prompt.to_s

Data Separation

# Clear separation between instructions and data
prompt = Artificial::Prompt.new(
  instructions: "Analyze the sales data and identify trends",
  data: {
    q1_sales: "100000",
    q2_sales: "120000",
    q3_sales: "110000",
    q4_sales: "130000"
  }
)
puts prompt.to_s

Tool Integration

# Function calling support
prompt = Artificial::Prompt.new("Calculate financial metrics")
  .with_tools(
    { name: "calculate_ratios", parameters: { data: "quarterly_reports" } },
    { name: "generate_chart", parameters: { chart_type: "trend" } }
  )
puts prompt.to_s

Message Arrays (Conversation Format)

# Multi-turn conversations
messages = [
  { role: "system", content: "You are a helpful Ruby programming assistant" },
  { role: "user", content: "How do I create a class in Ruby?" },
  { role: "assistant", content: "You can create a class using the 'class' keyword" },
  { role: "user", content: "Can you show me an example?" }
]

prompt = Artificial::Prompt.new(messages)
puts prompt.to_s

Multi-format Input Parsing

# YAML format
yaml_input = <<~YAML
  text: "Explain Ruby blocks"
  system: "You are a Ruby expert"
  context:
    audience: "beginners"
    goal: "education"
YAML

parsed = Artificial.parse(yaml_input)
puts parsed.to_hash[:text]  # "Explain Ruby blocks"

# JSON format
json_input = '{"text": "What are Ruby gems?", "system": "You are a Ruby expert"}'
parsed = Artificial.parse(json_input)
puts parsed.to_hash[:text]  # "What are Ruby gems?"

# Auto-detection
parsed = Artificial.parse("Simple text prompt")
puts parsed.to_hash[:format]  # "string"

Validation

# Message validation
messages = [
  { role: "system", content: "You are helpful" },
  { role: "user", content: "Hello" }
]

validator = Artificial.validate_messages(messages)
puts validator.valid?  # true

# Role validation with optimization suggestions
validator = Artificial.validate_role("You are a Ruby programming expert")
puts validator.valid?      # true
puts validator.effective?  # true
puts validator.optimization_suggestions.join("; ")

Long Context Documents

# Efficient handling of large documents
prompt = Artificial::Prompt.new("Summarize the key findings")
  .with_documents(
    {
      content: "Long research document content...",
      source: "research_report.pdf",
      metadata: { author: "Dr. Smith", date: "2024-01-15" }
    }
  )
puts prompt.to_s

Advanced Features

# Comprehensive prompt with all features
prompt = Artificial::Prompt.new(
  text: "Analyze this code",
  system: "You are a senior Ruby developer",
  context: {
    audience: "junior developers",
    goal: "identify improvements",
    workflow: "code_review"
  },
  examples: [
    { input: "bad_code.rb", output: "improvement_suggestions" }
  ],
  thinking: { enabled: true, style: "step_by_step" },
  grounding: {
    require_quotes: true,
    require_sources: true,
    allow_uncertainty: true
  },
  constraints: [
    "Quote specific code sections",
    "Provide actionable suggestions",
    "Consider performance implications"
  ]
)

puts prompt.to_s

API Reference

Artificial::Prompt

Main class for creating and managing prompts.

Methods

  • new(input = nil, **options) - Create a new prompt
  • to_s - Generate the final prompt string
  • with_system(system_prompt) - Set system prompt with role validation
  • with_context(**context_options) - Add contextual information
  • with_examples(*examples) - Add structured examples
  • with_thinking(enabled: true, style: 'step_by_step') - Enable step-by-step reasoning
  • with_grounding(**options) - Add hallucination prevention
  • with_constraints(*constraints) - Add explicit constraints
  • with_tools(*tools) - Add function calling tools
  • with_documents(*documents) - Add long context documents
  • with_data(data_hash) - Add data separate from instructions
  • with_prefill(text) - Set assistant response prefill

Artificial Module Methods

  • Artificial.create_prompt(input, **options) - Factory method for creating prompts
  • Artificial.parse(input, format: :auto) - Parse input in various formats
  • Artificial.validate_messages(messages) - Validate message array structure
  • Artificial.validate_role(system_prompt) - Validate and optimize role prompts

Advanced Usage

Custom Parsers

The gem supports multiple input formats with automatic detection:

# Explicit format specification
xml_parsed = Artificial.parse(xml_string, format: :xml)
yaml_parsed = Artificial.parse(yaml_string, format: :yaml)
json_parsed = Artificial.parse(json_string, format: :json)

# Auto-detection (recommended)
auto_parsed = Artificial.parse(input_string)  # Automatically detects format

Validation and Optimization

# Role optimization suggestions
validator = Artificial.validate_role("You are helpful")
puts validator.effective?  # false - generic role
puts validator.optimization_suggestions
# => ["Generic roles may reduce AI performance. Consider specifying domain expertise"]

# Effective role
validator = Artificial.validate_role("You are a Ruby programming expert with 10 years of experience")
puts validator.effective?  # true
puts validator.optimization_suggestions
# => ["Excellent! Domain expert roles typically improve response quality by 20-30%"]

Error Handling

begin
  # Invalid message structure
  messages = [{ role: "invalid", content: "test" }]
  Artificial::Prompt.new(messages)
rescue ArgumentError => e
  puts e.message  # "Message at index 0 has invalid role 'invalid'"
end

Examples

See the examples/demo.rb file for a comprehensive demonstration of all features.

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake test to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and the created tag, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/roboruby/artificial.

License

The gem is available as open source under the terms of the MIT License.

Performance Benefits

Based on industry best practices from Anthropic's research, this gem provides:

  • Reduced hallucinations through grounding requirements and source attribution
  • Better context handling for long documents (20K+ tokens)
  • Structured output that's easier to parse and validate
  • Optimized prompts that follow proven patterns for maximum effectiveness

Alignment with Industry Standards

This gem implements prompt engineering techniques aligned with:

  • Anthropic's Interactive Prompt Engineering Tutorial
  • OpenAI's best practices for function calling
  • Production-ready hallucination prevention strategies