Class: AISpec::Core::Providers::VLLM

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

Instance Attribute Summary

Attributes inherited from Base

#model, #options

Instance Method Summary collapse

Methods inherited from Base

get, register

Constructor Details

#initialize(model: "llama-4", endpoint: nil, api_key: nil, **options) ⇒ VLLM

Returns a new instance of VLLM.



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

def initialize(model: "llama-4", endpoint: nil, api_key: nil, **options)
  super(model: model, **options)
  @endpoint = endpoint || ENV["VLLM_API_BASE"] || ENV["VLLM_HOST"] || "http://localhost:8000/v1/chat/completions"
  @api_key = api_key || ENV["VLLM_API_KEY"]
end

Instance Method Details

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



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
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/aispec/core/providers/vllm.rb', line 17

def generate(prompt, system_prompt: nil, temperature: 0.7, **_params)
  uri = URI.parse(@endpoint)

  messages = []
  messages << { role: "system", content: system_prompt } if system_prompt
  messages << { role: "user", content: prompt }

  payload = {
    model: @model || "llama-4",
    messages: messages,
    temperature: temperature
  }

  start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  headers = { "Content-Type" => "application/json" }
  headers["Authorization"] = "Bearer #{@api_key}" if @api_key && !@api_key.empty?

  req = Net::HTTP::Post.new(uri.path.empty? ? "/v1/chat/completions" : uri.path, headers)
  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.dig("choices", 0, "message", "content") || ""
      prompt_tokens = data.dig("usage", "prompt_tokens") || 0
      comp_tokens = data.dig("usage", "completion_tokens") || 0
      total_tokens = data.dig("usage", "total_tokens") || (prompt_tokens + comp_tokens)

      build_response(
        output: output,
        latency_ms: elapsed_ms,
        tokens: total_tokens,
        cost: 0.0, # Local/Self-hosted vLLM infrastructure
        raw: data
      )
    else
      raise "vLLM API Error (#{res.code}): #{res.body}"
    end
  rescue Exception => e
    # If network connection fails or VCR/WebMock blocks connection in tests without active server, fallback to mock
    if is_network_or_mock_error?(e)
      Mock.new(model: @model).generate(prompt)
    else
      raise e
    end
  end
end