-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathChatGptTranslatorEndpoint.cs
More file actions
86 lines (71 loc) · 2.83 KB
/
ChatGptTranslatorEndpoint.cs
File metadata and controls
86 lines (71 loc) · 2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
using XUnity.AutoTranslator.Plugin.Core.Endpoints;
using XUnity.AutoTranslator.Plugin.Core.Endpoints.Http;
using XUnity.AutoTranslator.Plugin.Core.Web;
internal class ChatGptTranslatorEndpoint : HttpEndpoint
{
private string? _apiKey;
private string? _model;
private string? _prompt;
private string? _url;
public override string Id => "ChatGPTTranslate";
public override string FriendlyName => "ChatGPT Translate";
public override int MaxTranslationsPerRequest => 1;
public override int MaxConcurrency => 15;
public override void Initialize(IInitializationContext context)
{
_apiKey = context.GetOrCreateSetting("ChatGPT", "APIKey", "");
_model = context.GetOrCreateSetting("ChatGPT", "Model", "gpt-4o");
_prompt = context.GetOrCreateSetting("ChatGPT", "Prompt", "");
_url = context.GetOrCreateSetting("ChatGPT", "URL", "https://api.openai.com/v1/chat/completions");
// Remove artificial delays
context.SetTranslationDelay(0.1f);
context.DisableSpamChecks();
if (string.IsNullOrEmpty(_apiKey))
throw new Exception("The ChatGPT endpoint requires an API key which has not been provided.");
}
public override void OnCreateRequest(IHttpRequestCreationContext context)
{
var requestData = GetRequestData(context);
var request = new XUnityWebRequest("POST", _url, requestData);
request.Headers[HttpRequestHeader.Authorization] = $"Bearer {_apiKey}";
request.Headers[HttpRequestHeader.ContentType] = "application/json";
context.Complete(request);
}
private string GetRequestData(IHttpRequestCreationContext context)
{
var messages = new List<object>
{
new { role = "system", content = _prompt }
};
foreach (var text in context.UntranslatedTexts)
{
messages.Add(new { role = "user", content = text });
}
var requestBody = new
{
model = _model,
temperature = 0.1,
max_tokens = 1000,
top_p = 1,
frequency_penalty = 0,
presence_penalty = 0,
messages
};
return JsonConvert.SerializeObject(requestBody);
}
public override void OnExtractTranslation(IHttpTranslationExtractionContext context)
{
var data = context.Response.Data;
var jsonResponse = JObject.Parse(data);
if (MaxTranslationsPerRequest == 1)
context.Complete(GetTranslatedText(jsonResponse, 0));
}
private static string GetTranslatedText(JObject jsonResponse, int index)
{
var rawString = jsonResponse["choices"]?[index]?["message"]?["content"]?.ToString() ?? string.Empty;
return rawString.Trim();
}
}