Class: Prescient::Provider::HuggingFace

Inherits:
Base
  • Object
show all
Includes:
HTTParty
Defined in:
lib/prescient/provider/huggingface.rb

Constant Summary collapse

EMBEDDING_DIMENSIONS =
{
  'sentence-transformers/all-MiniLM-L6-v2'     => 384,
  'sentence-transformers/all-mpnet-base-v2'    => 768,
  'sentence-transformers/all-roberta-large-v1' => 1024,
}.freeze

Instance Attribute Summary

Attributes inherited from Base

#options

Instance Method Summary collapse

Methods inherited from Base

#available?

Constructor Details

#initialize(**options) ⇒ HuggingFace

Returns a new instance of HuggingFace.



16
17
18
19
# File 'lib/prescient/provider/huggingface.rb', line 16

def initialize(**options)
  super
  self.class.default_timeout(@options[:timeout] || 60)
end

Instance Method Details

#generate_embedding(text, **_options) ⇒ Object



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
# File 'lib/prescient/provider/huggingface.rb', line 21

def generate_embedding(text, **_options)
  handle_errors do
    clean_text_input = clean_text(text)

    response = self.class.post("/pipeline/feature-extraction/#{@options[:embedding_model]}",
                               headers: {
                                 'Content-Type'  => 'application/json',
                                 'Authorization' => "Bearer #{@options[:api_key]}",
                               },
                               body:    {
                                 inputs:  clean_text_input,
                                 options: {
                                   wait_for_model: true,
                                 },
                               }.to_json)

    validate_response!(response, 'embedding generation')

    # HuggingFace returns embeddings as nested arrays, get the first one
    embedding_data = response.parsed_response
    embedding_data = embedding_data.first if embedding_data.is_a?(Array) && embedding_data.first.is_a?(Array)

    raise Prescient::InvalidResponseError, 'No embedding returned' unless embedding_data.is_a?(Array)

    expected_dimensions = EMBEDDING_DIMENSIONS[@options[:embedding_model]] || 384
    normalize_embedding(embedding_data, expected_dimensions)
  end
end

#generate_response(prompt, context_items = [], **options) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/prescient/provider/huggingface.rb', line 50

def generate_response(prompt, context_items = [], **options)
  handle_errors do
    formatted_prompt = build_prompt(prompt, context_items)

    response = self.class.post("/models/#{@options[:chat_model]}",
                               headers: {
                                 'Content-Type'  => 'application/json',
                                 'Authorization' => "Bearer #{@options[:api_key]}",
                               },
                               body:    {
                                 inputs:     formatted_prompt,
                                 parameters: {
                                   max_new_tokens:   options[:max_tokens] || 2000,
                                   temperature:      options[:temperature] || 0.7,
                                   top_p:            options[:top_p] || 0.9,
                                   return_full_text: false,
                                 },
                                 options:    {
                                   wait_for_model: true,
                                 },
                               }.to_json)

    validate_response!(response, 'text generation')

    # HuggingFace returns different formats depending on the model
    generated_text = nil
    parsed_response = response.parsed_response

    if parsed_response.is_a?(Array) && parsed_response.first.is_a?(Hash)
      generated_text = parsed_response.first['generated_text']
    elsif parsed_response.is_a?(Hash)
      generated_text = parsed_response['generated_text'] || parsed_response['text']
    end

    raise Prescient::InvalidResponseError, 'No response generated' unless generated_text

    {
      response:        generated_text.strip,
      model:           @options[:chat_model],
      provider:        'huggingface',
      processing_time: nil,
      metadata:        {},
    }
  end
end

#health_checkObject



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/prescient/provider/huggingface.rb', line 96

def health_check
  handle_errors do
    # Test embedding model
    embedding_response = self.class.post("/pipeline/feature-extraction/#{@options[:embedding_model]}",
                                         headers: {
                                           'Authorization' => "Bearer #{@options[:api_key]}",
                                         },
                                         body:    { inputs: 'test' }.to_json)

    # Test chat model
    chat_response = self.class.post("/models/#{@options[:chat_model]}",
                                    headers: {
                                      'Authorization' => "Bearer #{@options[:api_key]}",
                                    },
                                    body:    {
                                      inputs:     'test',
                                      parameters: { max_new_tokens: 5 },
                                    }.to_json)

    embedding_healthy = embedding_response.success?
    chat_healthy = chat_response.success?

    {
      status:          embedding_healthy && chat_healthy ? 'healthy' : 'partial',
      provider:        'huggingface',
      embedding_model: {
        name:      @options[:embedding_model],
        available: embedding_healthy,
      },
      chat_model:      {
        name:      @options[:chat_model],
        available: chat_healthy,
      },
      ready:           embedding_healthy && chat_healthy,
    }
  end
rescue Prescient::ConnectionError => e
  {
    status:   'unavailable',
    provider: 'huggingface',
    error:    e.class.name,
    message:  e.message,
  }
end

#list_modelsObject



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/prescient/provider/huggingface.rb', line 141

def list_models
  # HuggingFace doesn't provide a simple API to list all models
  # Return the configured models
  [
    {
      name:       @options[:embedding_model],
      type:       'embedding',
      dimensions: EMBEDDING_DIMENSIONS[@options[:embedding_model]],
    },
    {
      name: @options[:chat_model],
      type: 'text-generation',
    },
  ]
end