Class: Train::Model
- Inherits:
-
Object
- Object
- Train::Model
- Defined in:
- lib/train.rb
Overview
Train::Model represents a connection to an AI model endpoint
Instance Attribute Summary collapse
-
#api_key ⇒ Object
Returns the value of attribute api_key.
-
#model_name ⇒ Object
Returns the value of attribute model_name.
-
#url ⇒ Object
Returns the value of attribute url.
Instance Method Summary collapse
-
#chat(prompt, system: "You are a helpful AI.") ⇒ String
Sends a chat message to the AI model.
-
#initialize(api_key:, url:, model_name:, model_id_changed: nil) ⇒ Model
constructor
A new instance of Model.
Constructor Details
#initialize(api_key:, url:, model_name:, model_id_changed: nil) ⇒ Model
Returns a new instance of Model.
56 57 58 59 60 61 62 63 |
# File 'lib/train.rb', line 56 def initialize(api_key:, url:, model_name:, model_id_changed: nil) @api_key = api_key @url = URI.parse(url) # 🔁 override if custom model ID provided default_id = Train::MODELS.get(model_name) @model_name = model_id_changed || default_id || model_name end |
Instance Attribute Details
#api_key ⇒ Object
Returns the value of attribute api_key.
54 55 56 |
# File 'lib/train.rb', line 54 def api_key @api_key end |
#model_name ⇒ Object
Returns the value of attribute model_name.
54 55 56 |
# File 'lib/train.rb', line 54 def model_name @model_name end |
#url ⇒ Object
Returns the value of attribute url.
54 55 56 |
# File 'lib/train.rb', line 54 def url @url end |
Instance Method Details
#chat(prompt, system: "You are a helpful AI.") ⇒ String
Sends a chat message to the AI model
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
# File 'lib/train.rb', line 72 def chat(prompt, system: "You are a helpful AI.") return Chat.start(self) if prompt == Chat::INPUT http = Net::HTTP.new(url.host, url.port) http.use_ssl = (url.scheme == "https") headers = { "Content-Type" => "application/json", "Authorization" => "Bearer #{api_key}" } body = { model: model_name, messages: [ { role: "system", content: system }, { role: "user", content: prompt } ] }.to_json response = http.post(url.path, body, headers) json = JSON.parse(response.body) json["choices"]&.first&.dig("message", "content") || "⚠️ No response" rescue => e "❌ Train error: #{e.message}" end |