update
This commit is contained in:
@@ -21,9 +21,21 @@ namespace Hallucinate.AI
|
||||
public class GeminiService : MonoBehaviour
|
||||
{
|
||||
public static GeminiService Instance { get; private set; }
|
||||
private int activeRequests = 0;
|
||||
private const int MAX_CONCURRENT_REQUESTS = 5;
|
||||
|
||||
[SerializeField] private string apiKey = "AQ.Ab8RN6I2hU_p8yHiPNNHtWzYBiLugbPP22gC6lzTWaYEWj4v0g"; // Replace with your key
|
||||
[SerializeField] private string geminiURL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-flash-latest:generateContent";
|
||||
[SerializeField] private string[] apiKeys = { "YOUR_KEY_1", "YOUR_KEY_2" };
|
||||
private int currentKeyIndex = 0;
|
||||
|
||||
[SerializeField] private string geminiURL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent";
|
||||
private float nextRequestTime = 0f;
|
||||
|
||||
private string[] fallbackDialogues = {
|
||||
"{ \"text\": \"Nice weather, isn't it?\", \"speedMod\": 0.0, \"suspicionMod\": -5.0 }",
|
||||
"{ \"text\": \"Did you hear something? Probably just a rat.\", \"speedMod\": 0.0, \"suspicionMod\": 2.0 }",
|
||||
"{ \"text\": \"I'm so tired of this shift.\", \"speedMod\": -0.1, \"suspicionMod\": 0.0 }",
|
||||
"{ \"text\": \"Don't forget the coffee break later.\", \"speedMod\": 0.0, \"suspicionMod\": -2.0 }"
|
||||
};
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
@@ -31,24 +43,50 @@ namespace Hallucinate.AI
|
||||
else { Destroy(gameObject); }
|
||||
}
|
||||
|
||||
private string GetNextKey()
|
||||
{
|
||||
if (apiKeys == null || apiKeys.Length == 0) return "";
|
||||
string key = apiKeys[currentKeyIndex];
|
||||
currentKeyIndex = (currentKeyIndex + 1) % apiKeys.Length;
|
||||
return key;
|
||||
}
|
||||
|
||||
public void GetResponse(string persona, string prompt, Action<string> onComplete)
|
||||
{
|
||||
if (Time.time < nextRequestTime)
|
||||
{
|
||||
Debug.LogWarning("[Gemini] API is cooling down. Using fallback.");
|
||||
onComplete?.Invoke(fallbackDialogues[UnityEngine.Random.Range(0, fallbackDialogues.Length)]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (activeRequests >= MAX_CONCURRENT_REQUESTS)
|
||||
{
|
||||
onComplete?.Invoke(fallbackDialogues[UnityEngine.Random.Range(0, fallbackDialogues.Length)]);
|
||||
return;
|
||||
}
|
||||
StartCoroutine(PostRequest(persona, prompt, onComplete));
|
||||
}
|
||||
|
||||
private IEnumerator PostRequest(string persona, string prompt, Action<string> onComplete)
|
||||
{
|
||||
activeRequests++;
|
||||
|
||||
string jsonInstruction = " Respond ONLY with a JSON object: { 'text': 'your dialogue', 'speedMod': 0.0, 'suspicionMod': 0.0 }.";
|
||||
string escapedPersona = persona.Replace("\"", "\\\"");
|
||||
string escapedPrompt = prompt.Replace("\"", "\\\"");
|
||||
|
||||
var jsonBody = $@"{{
|
||||
""systemInstruction"": {{""parts"": [{{ ""text"": ""{persona}"" }}]}},
|
||||
""contents"": [{{""parts"": [{{ ""text"": ""{prompt}"" }}]}}],
|
||||
""systemInstruction"": {{""parts"": [{{ ""text"": ""{escapedPersona} {jsonInstruction}"" }}]}},
|
||||
""contents"": [{{""parts"": [{{ ""text"": ""{escapedPrompt}"" }}]}}],
|
||||
""generationConfig"": {{
|
||||
""maxOutputTokens"": 60,
|
||||
""temperature"": 0.7
|
||||
""maxOutputTokens"": 100,
|
||||
""temperature"": 0.7,
|
||||
""responseMimeType"": ""application/json""
|
||||
}}
|
||||
}}";
|
||||
|
||||
var requestURL = $"{geminiURL}?key={apiKey}";
|
||||
|
||||
var requestURL = $"{geminiURL}?key={GetNextKey()}";
|
||||
|
||||
using (var request = new UnityWebRequest(requestURL, "POST"))
|
||||
{
|
||||
@@ -61,34 +99,25 @@ namespace Hallucinate.AI
|
||||
|
||||
if (request.result == UnityWebRequest.Result.Success)
|
||||
{
|
||||
string rawResponse = request.downloadHandler.text;
|
||||
try
|
||||
var response = JsonUtility.FromJson<GeminiResponse>(request.downloadHandler.text);
|
||||
if (response?.candidates?.Length > 0 && response.candidates[0].content?.parts?.Length > 0)
|
||||
{
|
||||
var response = JsonUtility.FromJson<GeminiResponse>(rawResponse);
|
||||
if (response != null &&
|
||||
response.candidates != null &&
|
||||
response.candidates.Length > 0 &&
|
||||
response.candidates[0].content != null &&
|
||||
response.candidates[0].content.parts != null &&
|
||||
response.candidates[0].content.parts.Length > 0)
|
||||
{
|
||||
onComplete?.Invoke(response.candidates[0].content.parts[0].text);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogWarning($"[Gemini] Response structure invalid or blocked. Raw: {rawResponse}");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.LogError($"[Gemini] JSON Parse Error: {e.Message}\nRaw Response: {rawResponse}");
|
||||
onComplete?.Invoke(response.candidates[0].content.parts[0].text);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.LogError($"[Gemini] API Error: {request.error}");
|
||||
if (request.responseCode == 429)
|
||||
{
|
||||
nextRequestTime = Time.time + 60f; // Lock API for 1 minute
|
||||
Debug.LogWarning("Quota Exceeded. API locked for 60s. Using fallback.");
|
||||
}
|
||||
onComplete?.Invoke(fallbackDialogues[UnityEngine.Random.Range(0, fallbackDialogues.Length)]);
|
||||
}
|
||||
}
|
||||
|
||||
activeRequests--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user