|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Diagnostics; |
| 4 | +using System.IO; |
| 5 | +using System.Threading.Tasks; |
| 6 | + |
| 7 | +namespace OpenAI_API |
| 8 | +{ |
| 9 | + /// <summary> |
| 10 | + /// Represents authentication to the OpenAPI API endpoint |
| 11 | + /// </summary> |
| 12 | + public class APIAuthentication |
| 13 | + { |
| 14 | + /// <summary> |
| 15 | + /// The API key, required to access the API endpoint. |
| 16 | + /// </summary> |
| 17 | + public string ApiKey { get; set; } |
| 18 | + /// <summary> |
| 19 | + /// The Organization ID to count API requests against. This can be found at https://beta.openai.com/account/org-settings. |
| 20 | + /// </summary> |
| 21 | + public string OpenAIOrganization { get; set; } |
| 22 | + |
| 23 | + /// <summary> |
| 24 | + /// Allows implicit casting from a string, so that a simple string API key can be provided in place of an instance of <see cref="APIAuthentication"/> |
| 25 | + /// </summary> |
| 26 | + /// <param name="key">The API key to convert into a <see cref="APIAuthentication"/>.</param> |
| 27 | + public static implicit operator APIAuthentication(string key) |
| 28 | + { |
| 29 | + return new APIAuthentication(key); |
| 30 | + } |
| 31 | + |
| 32 | + /// <summary> |
| 33 | + /// Instantiates a new Authentication object with the given <paramref name="apiKey"/>, which may be <see langword="null"/>. |
| 34 | + /// </summary> |
| 35 | + /// <param name="apiKey">The API key, required to access the API endpoint.</param> |
| 36 | + public APIAuthentication(string apiKey) |
| 37 | + { |
| 38 | + this.ApiKey = apiKey; |
| 39 | + } |
| 40 | + |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Instantiates a new Authentication object with the given <paramref name="apiKey"/>, which may be <see langword="null"/>. For users who belong to multiple organizations, you can specify which organization is used. Usage from these API requests will count against the specified organization's subscription quota. |
| 44 | + /// </summary> |
| 45 | + /// <param name="apiKey">The API key, required to access the API endpoint.</param> |
| 46 | + /// <param name="openAIOrganization">The Organization ID to count API requests against. This can be found at https://beta.openai.com/account/org-settings.</param> |
| 47 | + public APIAuthentication(string apiKey, string openAIOrganization) |
| 48 | + { |
| 49 | + this.ApiKey = apiKey; |
| 50 | + this.OpenAIOrganization = openAIOrganization; |
| 51 | + } |
| 52 | + |
| 53 | + private static APIAuthentication cachedDefault = null; |
| 54 | + |
| 55 | + /// <summary> |
| 56 | + /// The default authentication to use when no other auth is specified. This can be set manually, or automatically loaded via environment variables or a config file. <seealso cref="LoadFromEnv"/><seealso cref="LoadFromPath(string, string, bool)"/> |
| 57 | + /// </summary> |
| 58 | + public static APIAuthentication Default |
| 59 | + { |
| 60 | + get |
| 61 | + { |
| 62 | + if (cachedDefault != null) |
| 63 | + return cachedDefault; |
| 64 | + |
| 65 | + APIAuthentication auth = LoadFromEnv(); |
| 66 | + if (auth == null) |
| 67 | + auth = LoadFromPath(); |
| 68 | + if (auth == null) |
| 69 | + auth = LoadFromPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); |
| 70 | + |
| 71 | + cachedDefault = auth; |
| 72 | + return auth; |
| 73 | + } |
| 74 | + set |
| 75 | + { |
| 76 | + cachedDefault = value; |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + /// <summary> |
| 81 | + /// Attempts to load api key from environment variables, as "OPENAI_KEY" or "OPENAI_API_KEY". Also loads org if from "OPENAI_ORGANIZATION" if present. |
| 82 | + /// </summary> |
| 83 | + /// <returns>Returns the loaded <see cref="APIAuthentication"/> any api keys were found, or <see langword="null"/> if there were no matching environment vars.</returns> |
| 84 | + public static APIAuthentication LoadFromEnv() |
| 85 | + { |
| 86 | + string key = Environment.GetEnvironmentVariable("OPENAI_KEY"); |
| 87 | + |
| 88 | + if (string.IsNullOrEmpty(key)) |
| 89 | + { |
| 90 | + key = Environment.GetEnvironmentVariable("OPENAI_API_KEY"); |
| 91 | + |
| 92 | + if (string.IsNullOrEmpty(key)) |
| 93 | + return null; |
| 94 | + } |
| 95 | + |
| 96 | + string org = Environment.GetEnvironmentVariable("OPENAI_ORGANIZATION"); |
| 97 | + |
| 98 | + return new APIAuthentication(key, org); |
| 99 | + } |
| 100 | + |
| 101 | + /// <summary> |
| 102 | + /// Attempts to load api keys from a configuration file, by default ".openai" in the current directory, optionally traversing up the directory tree |
| 103 | + /// </summary> |
| 104 | + /// <param name="directory">The directory to look in, or <see langword="null"/> for the current directory</param> |
| 105 | + /// <param name="filename">The filename of the config file</param> |
| 106 | + /// <param name="searchUp">Whether to recursively traverse up the directory tree if the <paramref name="filename"/> is not found in the <paramref name="directory"/></param> |
| 107 | + /// <returns>Returns the loaded <see cref="APIAuthentication"/> any api keys were found, or <see langword="null"/> if it was not successful in finding a config (or if the config file didn't contain correctly formatted API keys)</returns> |
| 108 | + public static APIAuthentication LoadFromPath(string directory = null, string filename = ".openai", bool searchUp = true) |
| 109 | + { |
| 110 | + if (directory == null) |
| 111 | + directory = Environment.CurrentDirectory; |
| 112 | + |
| 113 | + string key = null; |
| 114 | + string org = null; |
| 115 | + var curDirectory = new DirectoryInfo(directory); |
| 116 | + |
| 117 | + while (key == null && curDirectory.Parent != null) |
| 118 | + { |
| 119 | + if (File.Exists(Path.Combine(curDirectory.FullName, filename))) |
| 120 | + { |
| 121 | + var lines = File.ReadAllLines(Path.Combine(curDirectory.FullName, filename)); |
| 122 | + foreach (var l in lines) |
| 123 | + { |
| 124 | + var parts = l.Split('=', ':'); |
| 125 | + if (parts.Length == 2) |
| 126 | + { |
| 127 | + switch (parts[0].ToUpper()) |
| 128 | + { |
| 129 | + case "OPENAI_KEY": |
| 130 | + key = parts[1].Trim(); |
| 131 | + break; |
| 132 | + case "OPENAI_API_KEY": |
| 133 | + key = parts[1].Trim(); |
| 134 | + break; |
| 135 | + case "OPENAI_ORGANIZATION": |
| 136 | + org = parts[1].Trim(); |
| 137 | + break; |
| 138 | + default: |
| 139 | + break; |
| 140 | + } |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + if (searchUp) |
| 146 | + { |
| 147 | + curDirectory = curDirectory.Parent; |
| 148 | + } |
| 149 | + else |
| 150 | + { |
| 151 | + break; |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + if (string.IsNullOrEmpty(key)) |
| 156 | + return null; |
| 157 | + |
| 158 | + return new APIAuthentication(key, org); |
| 159 | + } |
| 160 | + |
| 161 | + |
| 162 | + /// <summary> |
| 163 | + /// 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. |
| 164 | + /// </summary> |
| 165 | + /// <returns><see langword="true"/> if the api key is valid, or <see langword="false"/> if empty or not accepted by the OpenAI API.</returns> |
| 166 | + public async Task<bool> ValidateAPIKey() |
| 167 | + { |
| 168 | + if (string.IsNullOrEmpty(ApiKey)) |
| 169 | + return false; |
| 170 | + |
| 171 | + var api = new OpenAIAPI(this); |
| 172 | + |
| 173 | + List<Models.Model> results; |
| 174 | + |
| 175 | + try |
| 176 | + { |
| 177 | + results = await api.Models.GetModelsAsync(); |
| 178 | + } |
| 179 | + catch (Exception ex) |
| 180 | + { |
| 181 | + Debug.WriteLine(ex.ToString()); |
| 182 | + return false; |
| 183 | + } |
| 184 | + |
| 185 | + return (results.Count > 0); |
| 186 | + } |
| 187 | + |
| 188 | + } |
| 189 | + |
| 190 | + internal static class AuthHelpers |
| 191 | + { |
| 192 | + /// <summary> |
| 193 | + /// A helper method to swap out <see langword="null"/> <see cref="APIAuthentication"/> objects with the <see cref="APIAuthentication.Default"/> authentication, possibly loaded from ENV or a config file. |
| 194 | + /// </summary> |
| 195 | + /// <param name="auth">The specific authentication to use if not <see langword="null"/></param> |
| 196 | + /// <returns>Either the provided <paramref name="auth"/> or the <see cref="APIAuthentication.Default"/></returns> |
| 197 | + public static APIAuthentication ThisOrDefault(this APIAuthentication auth) |
| 198 | + { |
| 199 | + if (auth == null) |
| 200 | + auth = APIAuthentication.Default; |
| 201 | + |
| 202 | + return auth; |
| 203 | + } |
| 204 | + } |
| 205 | +} |
0 commit comments