Class: Prescient::Provider::OpenAI
- Includes:
- HTTParty
- Defined in:
- lib/prescient/provider/openai.rb
Overview
OpenAI API provider adapter.
Constant Summary collapse
- EMBEDDING_DIMENSIONS =
Known embedding dimensions for OpenAI embedding models.
{ 'text-embedding-3-small' => 1536, 'text-embedding-3-large' => 3072, 'text-embedding-ada-002' => 1536, }.freeze
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
-
#generate_embedding(text, **options) ⇒ Array<Float>
Generate an embedding through the OpenAI embeddings API.
-
#generate_response(prompt, context_items = [], **options) ⇒ Hash
Generate a response through the OpenAI chat completions API.
-
#health_check ⇒ Hash
Check OpenAI model availability via
/v1/models. -
#initialize(**options) ⇒ OpenAI
constructor
A new instance of OpenAI.
-
#list_models ⇒ Array<Hash>
List models available to the configured OpenAI account.
- #validate_configuration! ⇒ Object protected
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) ⇒ OpenAI
Returns a new instance of OpenAI.
18 19 20 21 |
# File 'lib/prescient/provider/openai.rb', line 18 def initialize(**) super self.class.default_timeout(@options[:timeout] || 60) end |
Instance Method Details
#generate_embedding(text, **options) ⇒ Array<Float>
Generate an embedding through the OpenAI embeddings API.
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 |
# File 'lib/prescient/provider/openai.rb', line 26 def (text, **) handle_errors do clean_text_input = clean_text(text) = [:model] || @options[:embedding_model] response = self.class.post('/v1/embeddings', headers: { 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{@options[:api_key]}", }, body: { model: , input: clean_text_input, encoding_format: 'float', }.to_json) validate_response!(response, 'embedding generation') = response.parsed_response.dig('data', 0, 'embedding') raise Prescient::InvalidResponseError, 'No embedding returned' unless expected_dimensions = EMBEDDING_DIMENSIONS[] || @options[:embedding_dimensions] unless expected_dimensions raise Prescient::Error, "Embedding dimensions are required for model #{}" end (, expected_dimensions) end end |
#generate_response(prompt, context_items = [], **options) ⇒ Hash
Generate a response through the OpenAI chat completions API.
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 95 96 97 98 99 |
# File 'lib/prescient/provider/openai.rb', line 61 def generate_response(prompt, context_items = [], **) handle_errors do formatted_prompt = build_prompt(prompt, context_items) response = self.class.post('/v1/chat/completions', headers: { 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{@options[:api_key]}", }, body: { model: [:model] || @options[:chat_model], messages: [ { role: 'user', content: formatted_prompt, }, ], max_tokens: [:max_tokens] || 2000, temperature: [:temperature] || 0.7, top_p: [:top_p] || 0.9, }.to_json) validate_response!(response, 'text generation') content = response.parsed_response.dig('choices', 0, 'message', 'content') raise Prescient::InvalidResponseError, 'No response generated' unless content { response: content.strip, model: [:model] || @options[:chat_model], provider: 'openai', processing_time: nil, metadata: { usage: response.parsed_response['usage'], finish_reason: response.parsed_response.dig('choices', 0, 'finish_reason'), }, } end end |
#health_check ⇒ Hash
Check OpenAI model availability via /v1/models.
reachable indicates the API answered successfully. ready indicates that
both configured models appear in the returned model list.
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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 |
# File 'lib/prescient/provider/openai.rb', line 107 def health_check handle_errors do response = self.class.get('/v1/models', headers: { 'Authorization' => "Bearer #{@options[:api_key]}", }) if response.success? models = response.parsed_response['data'] || [] = models.any? { |m| m['id'] == @options[:embedding_model] } chat_available = models.any? { |m| m['id'] == @options[:chat_model] } { status: 'healthy', provider: 'openai', reachable: true, models_available: models.map { |m| m['id'] }, embedding_model: { name: @options[:embedding_model], available: , }, chat_model: { name: @options[:chat_model], available: chat_available, }, ready: && chat_available, } else { status: 'unhealthy', provider: 'openai', reachable: true, error: "HTTP #{response.code}", message: response., ready: false, } end end rescue Prescient::Error => e { status: 'unavailable', provider: 'openai', reachable: false, error: e.class.name, message: e., ready: false, } end |
#list_models ⇒ Array<Hash>
List models available to the configured OpenAI account.
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 |
# File 'lib/prescient/provider/openai.rb', line 159 def list_models handle_errors do response = self.class.get('/v1/models', headers: { 'Authorization' => "Bearer #{@options[:api_key]}", }) validate_response!(response, 'model listing') models = response.parsed_response['data'] || [] models.map do |model| { name: model['id'], created: model['created'], owned_by: model['owned_by'], } end end end |
#validate_configuration! ⇒ Object (protected)
180 181 182 183 184 185 186 187 |
# File 'lib/prescient/provider/openai.rb', line 180 def validate_configuration! = [:api_key, :embedding_model, :chat_model] = .select { |opt| @options[opt].nil? } return unless .any? raise Prescient::Error, "Missing required options: #{.join(', ')}" end |