Skip to content

Commit f06833f

Browse files
authored
Configuration Loading Updates (#6)
**Added** - Auth data type for API key and organization info. - File check for auth.json. - Caching configuration object instead of creating it after script compilation. **Changed** - DallE sample project scene name changed.
1 parent b793265 commit f06833f

File tree

8 files changed

+37
-19
lines changed

8 files changed

+37
-19
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ private async void SendRequest()
5151
var request = new CreateCompletionRequest{
5252
Model="text-davinci-003",
5353
Prompt="Say this is a test",
54-
}
54+
};
5555
var response = await openai.CreateCompletion(request);
5656
}
5757
```

Runtime/Configuration.cs

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,38 @@
11
using System;
22
using System.IO;
3+
using UnityEngine;
34
using Newtonsoft.Json;
4-
using Newtonsoft.Json.Linq;
5+
using Newtonsoft.Json.Serialization;
56

67
namespace OpenAI
78
{
89
public class Configuration
910
{
10-
public string ApiKey { get; }
11-
public string Organization { get; }
11+
public Auth Auth { get; }
12+
13+
/// Used for serializing and deserializing PascalCase request object fields into snake_case format for JSON. Ignores null fields when creating JSON strings.
14+
private readonly JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
15+
{
16+
NullValueHandling = NullValueHandling.Ignore,
17+
ContractResolver = new DefaultContractResolver()
18+
{
19+
NamingStrategy = new CustomNamingStrategy()
20+
}
21+
};
1222

1323
public Configuration()
1424
{
15-
var path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
16-
var json = File.ReadAllText($"{path}/.openai/auth.json");
17-
var auth = JsonConvert.DeserializeObject<JToken>(json);
25+
var userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
26+
var authPath = $"{userPath}/.openai/auth.json";
1827

19-
if (auth != null)
28+
if (File.Exists(authPath))
2029
{
21-
ApiKey = auth["api_key"]!.Value<string>();
22-
Organization = auth["organization"]!.Value<string>();
30+
var json = File.ReadAllText(authPath);
31+
Auth = JsonConvert.DeserializeObject<Auth>(json, jsonSerializerSettings);
2332
}
2433
else
2534
{
26-
throw new Exception("auth.json could not be found.");
35+
Debug.LogError($"auth.json does not exist. Please check https://github.com/srcnalt/OpenAI-Unity#saving-your-credentials");
2736
}
2837
}
2938
}

Runtime/DataTypes.cs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System.Collections.Generic;
2+
using Newtonsoft.Json;
23

34
namespace OpenAI
45
{
@@ -42,6 +43,13 @@ public class ApiError
4243
public object Param;
4344
public object Code;
4445
}
46+
47+
public struct Auth
48+
{
49+
[JsonRequired]
50+
public string ApiKey { get; set; }
51+
public string Organization { get; set; }
52+
}
4553
#endregion
4654

4755
#region Models API Data Types

Runtime/OpenAIApi.cs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@ public class OpenAIApi
1515
/// Remember that your API key is a secret! Do not share it with others or expose it in any client-side code (browsers, apps).
1616
/// Production requests must be routed through your own backend server where your API key can be securely loaded from an environment variable or key management service.
1717
/// </summary>
18-
private readonly Configuration configuration = new Configuration();
19-
18+
private Configuration configuration;
19+
private Configuration Configuration => configuration ??= new Configuration();
20+
2021
/// OpenAI API base path for requests.
2122
private const string BASE_PATH = "https://api.openai.com/v1";
2223

@@ -42,7 +43,7 @@ public class OpenAIApi
4243
private async Task<T> DispatchRequest<T>(string path, HttpMethod method, byte[] payload = null) where T: IResponse
4344
{
4445
var client = new HttpClient();
45-
client.SetHeaders(configuration, ContentType.ApplicationJson);
46+
client.SetHeaders(Configuration, ContentType.ApplicationJson);
4647

4748
var request = new HttpRequestMessage(method, path);
4849
if (payload != null)
@@ -75,7 +76,7 @@ private async Task<T> DispatchRequest<T>(string path, HttpMethod method, byte[]
7576
private async Task<T> DispatchRequest<T>(string path, MultipartFormDataContent form) where T: IResponse
7677
{
7778
var client = new HttpClient();
78-
client.SetHeaders(configuration, ContentType.MultipartFormData);
79+
client.SetHeaders(Configuration, ContentType.MultipartFormData);
7980

8081
var response = await client.PostAsync(path, form);
8182
var content = await response.Content.ReadAsStringAsync();

Runtime/Utils/ExtensionMethods.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,11 +60,11 @@ public static void AddValue(this MultipartFormDataContent form, object value, st
6060
/// <param name="type">The value of the Accept header for an HTTP request.</param>
6161
public static void SetHeaders(this HttpClient client, Configuration configuration, string type)
6262
{
63-
if (configuration.Organization != null)
63+
if (configuration.Auth.Organization != null)
6464
{
65-
client.DefaultRequestHeaders.Add("OpenAI-Organization", configuration.Organization);
65+
client.DefaultRequestHeaders.Add("OpenAI-Organization", configuration.Auth.Organization);
6666
}
67-
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", configuration.ApiKey);
67+
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", configuration.Auth.ApiKey);
6868
client.DefaultRequestHeaders.Accept.Clear();
6969
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(type));
7070
}
File renamed without changes.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "com.srcnalt.openai-unity",
3-
"version": "0.1.1",
3+
"version": "0.1.2",
44
"displayName": "OpenAI Unity",
55
"description": "An unofficial OpenAI Unity Package that aims to help you use OpenAI API directly in Unity Game engine.",
66
"unity": "2020.3",

0 commit comments

Comments
 (0)