Skip to content

Commit

Permalink
Add API Key Validation and better API error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
OkGoDoIt committed Feb 3, 2023
1 parent f85c4ae commit 0876a15
Show file tree
Hide file tree
Showing 6 changed files with 61 additions and 5 deletions.
29 changes: 29 additions & 0 deletions OpenAI_API/APIAuthentication.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace OpenAI_API
{
Expand Down Expand Up @@ -156,6 +159,32 @@ public static APIAuthentication LoadFromPath(string directory = null, string fil
}


/// <summary>
/// Tests the api key against the OpenAI API, to ensure it is valid. This hits the models endpoint so should not be charged for usage.
/// </summary>
/// <returns><see langword="true"/> if the api key is valid, or <see langword="false"/> if empty or not accepted by the OpenAI API.</returns>
public async Task<bool> ValidateAPIKey()
{
if (string.IsNullOrEmpty(ApiKey))
return false;

var api = new OpenAIAPI(this);

List<Models.Model> results;

try
{
results = await api.Models.GetModelsAsync();
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
return false;
}

return (results.Count > 0);
}

}

internal static class AuthHelpers
Expand Down
13 changes: 12 additions & 1 deletion OpenAI_API/EndpointBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,18 @@ private async Task<HttpResponseMessage> HttpRequestRaw(string url = null, HttpMe
resultAsString = "Additionally, the following error was thrown when attemping to read the response content: " + e.ToString();
}

throw new HttpRequestException(GetErrorMessage(resultAsString, response, Endpoint, url));
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
throw new AuthenticationException("OpenAI rejected your authorization, most likely due to an invalid API Key. Try checking your API Key and see https://github.com/OkGoDoIt/OpenAI-API-dotnet#authentication for guidance. Full API response follows: " + resultAsString);
}
else if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError)
{
throw new HttpRequestException("OpenAI had an internal server error, which can happen occasionally. Please retry your request. " + GetErrorMessage(resultAsString, response, Endpoint, url));
}
else
{
throw new HttpRequestException(GetErrorMessage(resultAsString, response, Endpoint, url));
}
}
}

Expand Down
18 changes: 18 additions & 0 deletions OpenAI_Tests/AuthTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using NUnit.Framework;
using System;
using System.IO;
using System.Threading.Tasks;

namespace OpenAI_Tests
{
Expand Down Expand Up @@ -105,5 +106,22 @@ public void ParseKey()
Assert.AreEqual("orgTest", auth.OpenAIOrganization);
}

[Test]
public async Task TestBadKey()
{
var auth = new OpenAI_API.APIAuthentication("pk-testAA");
Assert.IsFalse(await auth.ValidateAPIKey());

auth = new OpenAI_API.APIAuthentication(null);
Assert.IsFalse(await auth.ValidateAPIKey());
}

[Test]
public async Task TestValidateGoodKey()
{
var auth = new OpenAI_API.APIAuthentication(Environment.GetEnvironmentVariable("TEST_OPENAI_SECRET_KEY"));
Assert.IsTrue(await auth.ValidateAPIKey());
}

}
}
1 change: 0 additions & 1 deletion OpenAI_Tests/CompletionEndpointTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using NUnit.Framework;
using OpenAI_API;
using System;
using System.Linq;
using System.Threading.Tasks;
Expand Down
1 change: 0 additions & 1 deletion OpenAI_Tests/EmbeddingEndpointTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using NUnit.Framework;
using OpenAI_API;
using OpenAI_API.Embedding;
using OpenAI_API.Models;
using System;
Expand Down
4 changes: 2 additions & 2 deletions OpenAI_Tests/ModelEndpointTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using OpenAI_API.Models;
using System;
using System.Linq;
using System.Net.Http;
using System.Security.Authentication;
using System.Threading.Tasks;

namespace OpenAI_Tests
Expand Down Expand Up @@ -66,7 +66,7 @@ public void GetEnginesAsync_ShouldFailIfInvalidAuthIsProvided()
var api = new OpenAIAPI(new APIAuthentication(Guid.NewGuid().ToString()));
Func<Task> act = () => api.Models.GetModelsAsync();
act.Should()
.ThrowAsync<HttpRequestException>()
.ThrowAsync<AuthenticationException>()
.Where(exc => exc.Message.Contains("Incorrect API key provided"));
}

Expand Down

0 comments on commit 0876a15

Please sign in to comment.