Class: Prescient::Provider::XAI

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

Overview

xAI API provider adapter.

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) ⇒ XAI

Returns a new instance of XAI.



11
12
13
14
15
# File 'lib/prescient/provider/xai.rb', line 11

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

Instance Method Details

#generate_embedding(_text, **_options) ⇒ Object

xAI does not expose a standard embeddings API for this adapter.

Raises:



19
20
21
# File 'lib/prescient/provider/xai.rb', line 19

def generate_embedding(_text, **_options)
  raise Prescient::Error, 'xAI provider does not support embeddings.'
end

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

Generate a response through xAI's OpenAI-compatible chat API.

Parameters:

  • prompt (String)

    Prompt to send

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

    Optional context items

Returns:

  • (Hash)

    Normalized response data



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

def generate_response(prompt, context_items = [], **options)
  handle_errors do
    model = options[:model] || @options[:chat_model]
    response = self.class.post(
      '/v1/chat/completions',
      headers: api_headers,
      body:    {
        model:       model,
        messages:    [{ role: 'user', content: build_prompt(prompt, context_items) }],
        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
    content = parsed_response.dig('choices', 0, 'message', 'content')
    raise Prescient::InvalidResponseError, 'No response generated' unless content.is_a?(String) && !content.empty?

    {
      response:        content.strip,
      model:           model,
      provider:        'xai',
      processing_time: nil,
      metadata:        {
        usage:         parsed_response['usage'],
        finish_reason: parsed_response.dig('choices', 0, 'finish_reason'),
      },
    }
  end
end

#health_checkHash

Check whether the configured xAI model is available.

Returns:

  • (Hash)

    Provider health information



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
95
96
97
98
99
# File 'lib/prescient/provider/xai.rb', line 63

def health_check
  handle_errors do
    response = self.class.get('/v1/models', headers: api_headers)

    if response.success?
      models = response.parsed_response['data'] || []
      model_available = models.any? { |model| model['id'] == @options[:chat_model] }

      {
        status:           'healthy',
        provider:         'xai',
        reachable:        true,
        models_available: models.map { |model| model['id'] },
        chat_model:       { name: @options[:chat_model], available: model_available },
        ready:            model_available,
      }
    else
      {
        status:    'unhealthy',
        provider:  'xai',
        reachable: true,
        error:     "HTTP #{response.code}",
        message:   response.message,
        ready:     false,
      }
    end
  end
rescue Prescient::Error => e
  {
    status:    'unavailable',
    provider:  'xai',
    reachable: false,
    error:     e.class.name,
    message:   e.message,
    ready:     false,
  }
end

#list_modelsArray<Hash>

List models available to the configured xAI API key.

Returns:

  • (Array<Hash>)

    Model descriptors



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/prescient/provider/xai.rb', line 103

def list_models
  handle_errors do
    response = self.class.get('/v1/models', headers: api_headers)
    validate_response!(response, 'model listing')

    (response.parsed_response['data'] || []).map do |model|
      {
        name:           model['id'],
        object:         model['object'],
        created:        model['created'],
        owned_by:       model['owned_by'],
        context_length: model['context_length'],
      }.compact
    end
  end
end

#validate_configuration!Object (protected)

Raises:



122
123
124
125
126
127
128
129
# File 'lib/prescient/provider/xai.rb', line 122

def validate_configuration!
  required_options = [:api_key, :chat_model]
  missing_options = required_options.select { |option| @options[option].nil? }

  return unless missing_options.any?

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