Skip to content

Commit bd05164

Browse files
committed
Improve API validation error examples
1 parent 7af6deb commit bd05164

2 files changed

Lines changed: 34 additions & 10 deletions

File tree

examples/15_proxy.rb

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,37 @@
1111
puts "\n=== AI::Chat Proxy Examples ==="
1212
puts
1313

14-
puts "0. Validate API key:"
15-
chat = AI::Chat.new(api_key_env_var: "PROXY_API_KEY")
16-
chat.proxy = true
17-
chat.user("What's the capital of Florida?")
18-
chat.generate![:content]
19-
puts " API Key validated: #{chat.instance_variable_get(:@api_key_validated)}"
14+
puts "0. Validates API key:"
15+
chat0 = AI::Chat.new(api_key_env_var: "PROXY_API_KEY")
16+
chat0.proxy = true
17+
chat0.user("What's the capital of Florida?")
18+
chat0.generate![:content]
19+
puts " API Key validated: #{chat0.instance_variable_get(:@api_key_validated)}"
20+
puts
21+
22+
puts "0.a Validates API key when invalid key used and proxy disabled:"
23+
chat0a = AI::Chat.new(api_key_env_var: "PROXY_API_KEY")
24+
chat0a.user("What's the capital of Florida?")
25+
begin
26+
chat0a.generate![:content]
27+
puts "✗ API validation should have failed"
28+
rescue AI::Chat::WrongAPITokenUsedError => e
29+
puts "✓ API validation correctly rejects call: #{e.message}"
30+
end
2031
puts
2132

33+
puts "0.b Validates API key when invalid key used and proxy enabled:"
34+
chat0b = AI::Chat.new
35+
chat0b.proxy = true
36+
chat0b.user("What's the capital of Florida?")
37+
begin
38+
chat0b.generate![:content]
39+
puts "✗ API validation should have failed"
40+
rescue AI::Chat::WrongAPITokenUsedError => e
41+
puts "✓ API validation correctly rejects call: #{e.message}"
42+
end
43+
puts
44+
exit 0
2245
puts "1. Basic conversation:"
2346
chat = AI::Chat.new(api_key_env_var: "PROXY_API_KEY")
2447
chat.proxy = true

lib/ai/chat.rb

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -572,16 +572,17 @@ def validate_api_key
572572
# Simple API call to validate the token
573573
client.models.list
574574
@api_key_validated = true
575-
rescue OpenAI::Errors::AuthenticationError => e
576-
if proxy
577-
raise WrongAPITokenUsedError, <<~STRING
575+
rescue OpenAI::Errors::AuthenticationError
576+
message = if proxy
577+
<<~STRING
578578
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.
579579
STRING
580580
else
581-
raise WrongAPITokenUsedError, <<~STRING
581+
<<~STRING
582582
It looks like you're using an invalid API key. Check to make sure your API key is valid before generating a response.
583583
STRING
584584
end
585+
raise WrongAPITokenUsedError, message, cause: nil
585586
end
586587

587588
# :reek:FeatureEnvy

0 commit comments

Comments
 (0)