83 lines
2.5 KiB
C#
83 lines
2.5 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Text;
|
|
using UnityEngine;
|
|
using UnityEngine.InputSystem;
|
|
using UnityEngine.Networking;
|
|
|
|
[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 GerminiNPC :MonoBehaviour
|
|
{
|
|
[SerializeField]
|
|
private string apiKey = "AQ.Ab8RN6I2hU_p8yHiPNNHtWzYBiLugbPP22gC6lzTWaYEWj4v0g";
|
|
[SerializeField]
|
|
private string germiniURL =
|
|
"https://generativelanguage.googleapis.com/v1beta/models/gemini-flash-latest:generateContent";
|
|
|
|
public string npcPersona =
|
|
$"Nguơi là ột thợ lão thợ rèn cọc cằn tên là TOm,ngươi rất ghét những kẻ mang phế liệu đến tiệm của mình.Ch trả lời ngắn gọn trong 2 câu,theo phong cách trung cổ";
|
|
|
|
public string playerHeldItem = "Thanh kiếm rỉ sét";
|
|
|
|
private void Update()
|
|
{
|
|
if (Keyboard.current.spaceKey.wasPressedThisFrame)
|
|
{
|
|
StartCoroutine(GetGerminiReponse());
|
|
}
|
|
}
|
|
|
|
private IEnumerator GetGerminiReponse()
|
|
{
|
|
var jsonBody = $@"{{""systemInstruction"": {{""parts"": [{{ ""text"": ""{npcPersona}"" }}]}},
|
|
""contents"": [{{""parts"": [{{ ""text"": ""Ta muốn bán cho ông món đồ này cho ông {playerHeldItem}""}}]}}] }} ";
|
|
var requestURL = $"{germiniURL}?ket={apiKey}";
|
|
using (var request = new UnityWebRequest(germiniURL, "POST"))
|
|
{
|
|
var 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.ProtocolError)
|
|
{
|
|
Debug.LogError(request.error);
|
|
}
|
|
else
|
|
{
|
|
var responseTEXT = request.downloadHandler.text;
|
|
var germiniResponse=JsonUtility.FromJson<GeminiResponse>(responseTEXT);
|
|
if (germiniResponse.candidates.Length > 0)
|
|
{
|
|
var npcResponse = germiniResponse.candidates[0].content.parts[0].text;
|
|
Debug.Log(npcResponse);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|