This commit is contained in:
2026-06-05 14:57:25 +07:00
parent 9499efe518
commit 05187d12a7
10 changed files with 654 additions and 104 deletions

View File

@@ -0,0 +1,76 @@
using System;
using System.Collections;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
namespace Hallucinate.AI
{
[Serializable]
public class Part { public string text; }
[Serializable]
public class Content { public Part[] parts; }
[Serializable]
public class Candidate { public Content content; }
[Serializable]
public class GeminiResponse { public Candidate[] candidates; }
public class GeminiService : MonoBehaviour
{
public static GeminiService Instance { get; private set; }
[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";
private void Awake()
{
if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); }
else { Destroy(gameObject); }
}
public void GetResponse(string persona, string prompt, Action<string> onComplete)
{
StartCoroutine(PostRequest(persona, prompt, onComplete));
}
private IEnumerator PostRequest(string persona, string prompt, Action<string> onComplete)
{
var jsonBody = $@"{{
""systemInstruction"": {{""parts"": [{{ ""text"": ""{persona}"" }}]}},
""contents"": [{{""parts"": [{{ ""text"": ""{prompt}"" }}]}}]
}}";
var requestURL = $"{geminiURL}?key={apiKey}";
using (var request = new UnityWebRequest(requestURL, "POST"))
{
byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonBody);
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
try
{
var response = JsonUtility.FromJson<GeminiResponse>(request.downloadHandler.text);
if (response?.candidates != null && response.candidates.Length > 0)
{
onComplete?.Invoke(response.candidates[0].content.parts[0].text);
}
}
catch (Exception e) { Debug.LogError($"[Gemini] JSON Parse Error: {e.Message}"); }
}
else
{
Debug.LogError($"[Gemini] API Error: {request.error}");
}
}
}
}
}