LlamaHair Ruby
Ruby implementation of the LlamaHair library for interacting with the LlamaHair API.
Installation
Add this line to your application's Gemfile:
gem 'llamahair'And then execute:
$ bundle installUsage
Basic Client Usage
Initialize the client with your API credentials:
client = LlamaHair::Client.new(
LlamaHair::Types::ClientOptions.new(
api_key_id: 'your_api_key_id',
api_key_secret: 'your_api_key_secret'
)
)You can also use environment variables:
LLAMAHAIR_API_KEY_IDLLAMAHAIR_API_SECRET
Sending Requests
Send a request to a specific prompt:
request = LlamaHair::Types::SendRequest.new(
llama: LlamaHair::Types::Llama.new(
id: 'unique_id',
body: 'Your prompt text here'
)
)
response = client.send('https://api.llamahair.ai/prompts/your-prompt', request)
puts response.job_idRetrieving Results
Retrieve results using a job ID:
request = LlamaHair::Types::OutputRequest.new(job_id: 'your_job_id')
response = client.retrieve(request)
puts response.response.output if response.response.output
puts response.response.outputs if response.response.outputs
puts response.response.summary if response.response.summarySend and Retrieve in One Call
response = client.send_and_retrieve(
'https://api.llamahair.ai/prompts/your-prompt',
request
)Webhook Validation
Add webhook validation to your Rails controller:
class WebhooksController < ApplicationController
skip_before_action :verify_authenticity_token
def create
validator = LlamaHair::WebhookValidator.new(
LlamaHair::Types::WebhookOptions.new(secret: ENV['WEBHOOK_SECRET'])
)
unless validator.verify(request)
return head :unauthorized
end
# Process the webhook
head :ok
end
endThe validator:
- Automatically verifies webhook signatures
- Handles both
X-Webhook-SignatureandHTTP_X_WEBHOOK_SIGNATUREheaders - Logs validation errors to Rails logger
- Uses secure comparison for signature verification
Error Handling
The library provides specific error classes for different scenarios:
begin
response = client.send_and_retrieve(prompt_url, request)
rescue LlamaHair::TimeoutError => e
puts "Request timed out: #{e.message}"
rescue LlamaHair::AuthenticationError => e
puts "Authentication failed: #{e.message}"
rescue LlamaHair::RequestError => e
puts "Request failed: #{e.message}"
rescue LlamaHair::InvalidResponseError => e
puts "Invalid response: #{e.message}"
rescue LlamaHair::Error => e
puts "Unexpected error: #{e.message}"
endDevelopment
After checking out the repo, run bundle install to install dependencies. Then:
- Run
rake specto run the tests - Run
rake rubocopto check code style - Run
rake testto run both tests and style checks
License
See the LICENSE file for details.