Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions examples/15_proxy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@
puts "\n=== AI::Chat Proxy Examples ==="
puts

puts "0. Validate API key:"
chat = AI::Chat.new(api_key_env_var: "PROXY_API_KEY")
chat.proxy = true
chat.user("What's the capital of Florida?")
chat.generate![:content]
puts " API Key validated: #{chat.instance_variable_get(:@api_key_validated)}"
puts

puts "1. Basic conversation:"
chat = AI::Chat.new(api_key_env_var: "PROXY_API_KEY")
chat.proxy = true
Expand Down
27 changes: 10 additions & 17 deletions lib/ai/chat.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def initialize(api_key: nil, api_key_env_var: "OPENAI_API_KEY")
@last_response_id = nil
@image_generation = false
@image_folder = "./images"
@api_key_validated = false
end

def self.generate_schema!(description, location: "schema.json", api_key: nil, api_key_env_var: "OPENAI_API_KEY", proxy: false)
Expand Down Expand Up @@ -133,7 +134,7 @@ def assistant(message, response: nil, status: nil)
# :reek:NilCheck
# :reek:TooManyStatements
def generate!
validate_api_key
validate_api_key unless @api_key_validated
response = create_response
parse_response(response)

Expand Down Expand Up @@ -568,25 +569,17 @@ def warn_if_file_fails_to_save
end

def validate_api_key
openai_api_key_used = @api_key.start_with?("sk-proj")
proxy_api_key_used = !openai_api_key_used
proxy_enabled = proxy
proxy_disabled = !proxy

if openai_api_key_used && proxy_enabled
# Simple API call to validate the token
client.models.list
@api_key_validated = true
rescue OpenAI::Errors::AuthenticationError => e
if proxy
raise WrongAPITokenUsedError, <<~STRING
It looks like you're using an official API key from OpenAI with proxying enabled. When proxying is enabled you must use an OpenAI API key from prepend.me. Please disable proxy or update your API key before generating a response.
It looks like you're using an invalid API key. Proxying is enabled, so you must use an OpenAI API key from prepend.me. Please disable proxy or update your API key before generating a response.
STRING
elsif proxy_api_key_used && proxy_disabled
else
raise WrongAPITokenUsedError, <<~STRING
It looks like you're using an unofficial OpenAI API key from prepend.me. When using an unofficial API key you must enable proxy before generating a response. Proxying is currently disabled, please enable it before generating a response.

Example:

chat = AI::Chat.new
chat.proxy = true
chat.user(...)
chat.generate!
It looks like you're using an invalid API key. Check to make sure your API key is valid before generating a response.
STRING
end
end
Expand Down