"error": {
"code": 403,
"message": "Метод не позволяет незарегистрированным вызывающим абонентам (вызывающим абонентам без установленной идентификации). Используйте API-ключ или другую форму API
идентификатора потребителя для вызова этого API.",
"status": "PERMISSION_DENIED"
Это URL-адреса, которые я использую:
Код: Выделить всё
private string apiEndpoint = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent"; // Edit it and choose your prefer model
private string imageEndpoint = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp-image-generation:generateContent"; //End point for image generation
Код: Выделить всё
private IEnumerator SendPromptRequestToGeminiImageGenerator(string promptText, string mediaPath)
{
string url = $"{imageEndpoint}?key={apiKey}";
byte[] mediaBytes = File.ReadAllBytes(mediaPath);
string base64Media = System.Convert.ToBase64String(mediaBytes);
string mimeTypeMedia = GetMimeTypeString();
string jsonData = $@"{{
""contents"": [
{{
""parts"": [
{{
""text"": ""{promptText}""
}},
{{
""inline_data"": {{
""mime_type"": ""{mimeTypeMedia}"",
""data"": ""{base64Media}""
}}
}}
]
}}
],
""generation_config"": {{
""response_modalities"": [""TEXT"", ""IMAGE""]
}}
}}";
byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(jsonData);
// Create a UnityWebRequest with the JSON data
using (UnityWebRequest www = new UnityWebRequest(url, "POST"))
{
www.uploadHandler = new UploadHandlerRaw(jsonToSend);
www.downloadHandler = new DownloadHandlerBuffer();
www.SetRequestHeader("Content-Type", "application/json");
yield return www.SendWebRequest();
if (www.result != UnityWebRequest.Result.Success)
{
Debug.Log("error in request");
Debug.LogError(www.error);
Debug.LogError(www.result);
Debug.LogError(www.responseCode);
Debug.LogError("Response: " + www.downloadHandler.text);
errorResponseRecevied?.Invoke(www.error);
}
else
{
Debug.Log("Request complete!");
Debug.Log("Full response: " + www.downloadHandler.text); // Log full response for debugging
// Parse the JSON response
try
{
ImageResponse response = JsonUtility.FromJson(www.downloadHandler.text);
if (response.candidates != null && response.candidates.Length > 0 &&
response.candidates[0].content != null &&
response.candidates[0].content.parts != null)
{
foreach (var part in response.candidates[0].content.parts)
{
if (!string.IsNullOrEmpty(part.text))
{
Debug.Log("Text response: " + part.text);
}
else if (part.inlineData != null && !string.IsNullOrEmpty(part.inlineData.data))
{
// This is the base64 encoded image data
byte[] imageBytes = System.Convert.FromBase64String(part.inlineData.data);
// Create a texture from the bytes
Texture2D tex = new Texture2D(2, 2);
tex.LoadImage(imageBytes);
byte[] pngBytes = tex.EncodeToPNG();
string path = Application.persistentDataPath + "/gemini-image.png";
File.WriteAllBytes(path, pngBytes);
Debug.Log("Saved to: " + path);
Debug.Log("Image received successfully!");
imageResponseRecevied?.Invoke(pngBytes);
}
}
}
else
{
Debug.Log("No valid response parts found.");
errorResponseRecevied?.Invoke("No valid response parts found.");
}
}
catch (Exception e)
{
Debug.LogError("JSON Parse Error: " + e.Message);
errorResponseRecevied?.Invoke(e.Message);
}
}
}
}
Я только что создал ключ Gemini с этого сайта. https://aistudio.google.com/app/api-keys
Нужно ли мне что-нибудь еще?
Подробнее здесь: https://stackoverflow.com/questions/797 ... -without-e
Мобильная версия