Class: AISpec::Core::Providers::Ollama

Inherits:
Base
  • Object
show all
Defined in:
lib/aispec/core/providers/ollama.rb

Instance Attribute Summary

Attributes inherited from Base

#model, #options

Instance Method Summary collapse

Methods inherited from Base

get, register

Constructor Details

#initialize(model: "llama3", host: nil, **options) ⇒ Ollama

Returns a new instance of Ollama.



11
12
13
14
# File 'lib/aispec/core/providers/ollama.rb', line 11

def initialize(model: "llama3", host: nil, **options)
  super(model: model, **options)
  @host = host || ENV["OLLAMA_HOST"] || "http://localhost:11434"
end

Instance Method Details

#generate(prompt, system_prompt: nil, **_params) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/aispec/core/providers/ollama.rb', line 16

def generate(prompt, system_prompt: nil, **_params)
  uri = URI.parse("#{@host.sub(/\/$/, '')}/api/generate")
  
  payload = {
    model: @model || "llama3",
    prompt: prompt,
    stream: false
  }
  payload[:system] = system_prompt if system_prompt

  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  req = Net::HTTP::Post.new(uri.path, { "Content-Type" => "application/json" })
  req.body = JSON.generate(payload)

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == "https"
  http.read_timeout = AISpec.configuration.timeout

  begin
    res = http.request(req)
    elapsed_ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time) * 1000.0

    if res.is_a?(Net::HTTPSuccess)
      data = JSON.parse(res.body)
      output = data["response"] || ""
      eval_count = data["eval_count"] || (output.split.length * 1.3).to_i

      build_response(
        output: output,
        latency_ms: elapsed_ms,
        tokens: eval_count,
        cost: 0.0, # Local execution cost $0.00
        raw: data
      )
    else
      raise "Ollama Error (#{res.code}): #{res.body}"
    end
  rescue Errno::ECONNREFUSED
    # Fallback to mock if local Ollama daemon is offline during dev/test
    Mock.new(model: @model).generate(prompt)
  end
end