Class: Prescient::Provider::HuggingFace

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

Overview

Hugging Face router-backed Inference Providers API adapter.

Constant Summary collapse

FEATURE_EXTRACTION_PATH =

Router path for the Hugging Face feature-extraction provider.

Returns:

  • (String)

    Feature-extraction endpoint template

'/hf-inference/models/%<model>s/pipeline/feature-extraction'
CHAT_COMPLETIONS_PATH =

OpenAI-compatible router path for Hugging Face chat completions.

Returns:

  • (String)

    Chat-completions endpoint path

'/v1/chat/completions'
MODEL_LIST_PATH =

OpenAI-compatible router path for listing available chat models.

Returns:

  • (String)

    Model-list endpoint path

'/v1/models'
EMBEDDING_DIMENSIONS =

Known embedding dimensions for commonly used models.

{
  '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, #provider_name

Instance Method Summary collapse

Methods inherited from Base

#available?, #build_prompt, #clean_text, #default_context_configs, #default_prompt_templates, #extract_embedding_text, #extract_text_values, #format_context_item, #handle_errors, #validate_embedding_dimensions

Constructor Details

#initialize(**options) ⇒ HuggingFace

Returns a new instance of HuggingFace.



30
31
32
33
# File 'lib/prescient/provider/huggingface.rb', line 30

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

Instance Method Details

#generate_embedding(text, **options) ⇒ Array<Float>

Generate an embedding through Hugging Face feature extraction.

Parameters:

  • text (String)

    Text to embed

Returns:

  • (Array<Float>)

    Embedding vector



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

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

    embedding_model = options[:model] || @options[:embedding_model]
    response = self.class.post(FEATURE_EXTRACTION_PATH % { model: embedding_model },
                               headers: {
                                 'Content-Type'  => 'application/json',
                                 'Authorization' => "Bearer #{@options[:api_key]}",
                               },
                               body:    { inputs: clean_text_input }.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[embedding_model] || @options[:embedding_dimensions]
    unless expected_dimensions
      raise Prescient::Error,
            "Embedding dimensions are required for model #{embedding_model}"
    end

    validate_embedding_dimensions(embedding_data, expected_dimensions)
  end
end

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

Generate text through a Hugging Face text-generation model.

Parameters:

  • prompt (String)

    Prompt to send

  • context_items (Array<Hash, String>) (defaults to: [])

    Optional context items

Returns:

  • (Hash)

    Normalized response data



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
98
99
100
101
102
103
104
105
106
# File 'lib/prescient/provider/huggingface.rb', line 72

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

    response = self.class.post(CHAT_COMPLETIONS_PATH,
                               headers: {
                                 'Content-Type'  => 'application/json',
                                 'Authorization' => "Bearer #{@options[:api_key]}",
                               },
                               body:    {
                                 model:       options[:model] || @options[:chat_model],
                                 messages:    [{ role: 'user', content: formatted_prompt }],
                                 max_tokens:  options[:max_tokens] || 2000,
                                 temperature: options[:temperature] || 0.7,
                                 top_p:       options[:top_p] || 0.9,
                               }.to_json)

    validate_response!(response, 'text generation')

    parsed_response = response.parsed_response
    generated_text = parsed_response.dig('choices', 0, 'message', 'content') if parsed_response.is_a?(Hash)
    raise Prescient::InvalidResponseError, 'No response generated' unless generated_text

    {
      response:        generated_text.strip,
      model:           options[:model] || @options[:chat_model],
      provider:        'huggingface',
      processing_time: nil,
      metadata:        {
        usage:         parsed_response['usage'],
        finish_reason: parsed_response.dig('choices', 0, 'finish_reason'),
      },
    }
  end
end

#health_checkHash

Check availability of the configured embedding and text models.

The embedding model is checked against the model metadata API on huggingface.co, while the chat model is checked against the router's OpenAI-compatible /v1/models listing. ready requires both checks to succeed.

Returns:

  • (Hash)

    Provider health information



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/prescient/provider/huggingface.rb', line 116

def health_check
  handle_errors do
    embedding_response = self.class.get("https://huggingface.co/api/models/#{@options[:embedding_model]}",
                                        headers: { 'Authorization' => "Bearer #{@options[:api_key]}" })
    chat_response = self.class.get(MODEL_LIST_PATH,
                                   headers: { 'Authorization' => "Bearer #{@options[:api_key]}" })

    embedding_healthy = embedding_response.success?
    chat_models = chat_response.parsed_response['data'] || []
    chat_healthy = chat_response.success? && chat_models.any? { |model| model['id'] == @options[:chat_model] }

    {
      status:          embedding_healthy && chat_healthy ? 'healthy' : 'partial',
      provider:        'huggingface',
      reachable:       true,
      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::Error => e
  {
    status:    'unavailable',
    provider:  'huggingface',
    reachable: false,
    error:     e.class.name,
    message:   e.message,
    ready:     false,
  }
end

#list_modelsArray<Hash>

Return the configured Hugging Face models.

This method does not query the Hugging Face APIs. It reflects the current adapter configuration only.

Returns:

  • (Array<Hash>)

    Model descriptors



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/prescient/provider/huggingface.rb', line 159

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

#validate_configuration!Object (protected)

Raises:



177
178
179
180
181
182
# File 'lib/prescient/provider/huggingface.rb', line 177

def validate_configuration!
  missing_options = [:api_key, :embedding_model, :chat_model].select { |opt| @options[opt].nil? }
  return unless missing_options.any?

  raise Prescient::Error, "Missing required options: #{missing_options.join(', ')}"
end