falta o esqueci a palavra passe
This commit is contained in:
@@ -1,42 +1,31 @@
|
||||
package com.example.cuida.services;
|
||||
|
||||
import com.google.ai.client.generativeai.GenerativeModel;
|
||||
import com.google.ai.client.generativeai.java.GenerativeModelFutures;
|
||||
import com.google.ai.client.generativeai.type.Content;
|
||||
import com.google.ai.client.generativeai.type.GenerateContentResponse;
|
||||
import com.google.ai.client.generativeai.type.HarmCategory;
|
||||
import com.google.ai.client.generativeai.type.SafetySetting;
|
||||
import com.google.ai.client.generativeai.type.BlockThreshold;
|
||||
import com.google.common.util.concurrent.FutureCallback;
|
||||
import com.google.common.util.concurrent.Futures;
|
||||
import com.google.common.util.concurrent.ListenableFuture;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.Executors;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import okhttp3.Call;
|
||||
import okhttp3.Callback;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.Response;
|
||||
|
||||
public class Gemini {
|
||||
private final GenerativeModelFutures modelo;
|
||||
private static final String API_KEY = "AIzaSyBmLgn-SHaTDvAeDWsw2iTZRR9gahhOu7k";
|
||||
private static final String MODEL_NAME = "gemini-flash-latest"; // O gemini-1.5-flash foi descontinuado e removido da API
|
||||
private static final String API_URL = "https://generativelanguage.googleapis.com/v1beta/models/" + MODEL_NAME + ":generateContent?key=" + API_KEY;
|
||||
private final OkHttpClient client;
|
||||
private final Handler mainHandler;
|
||||
|
||||
public Gemini() {
|
||||
// 1. Configurar Segurança (Padrão para evitar bloqueio de termos médicos)
|
||||
List<SafetySetting> safetySettings = Arrays.asList(
|
||||
new SafetySetting(HarmCategory.HARASSMENT, BlockThreshold.NONE),
|
||||
new SafetySetting(HarmCategory.HATE_SPEECH, BlockThreshold.NONE),
|
||||
new SafetySetting(HarmCategory.SEXUALLY_EXPLICIT, BlockThreshold.NONE),
|
||||
new SafetySetting(HarmCategory.DANGEROUS_CONTENT, BlockThreshold.NONE)
|
||||
);
|
||||
|
||||
// 2. Modelo (Simplificado ao máximo para garantir compilação)
|
||||
GenerativeModel generativeModel = new GenerativeModel(
|
||||
"gemini-1.5-flash",
|
||||
"AIzaSyBmLgn-SHaTDvAeDWsw2iTZRR9gahhOu7k",
|
||||
null, // Usamos o GenerationConfig padrão para evitar erro de setTemperature
|
||||
safetySettings
|
||||
);
|
||||
|
||||
this.modelo = GenerativeModelFutures.from(generativeModel);
|
||||
this.client = new OkHttpClient();
|
||||
this.mainHandler = new Handler(Looper.getMainLooper());
|
||||
}
|
||||
|
||||
public interface GeminiCallback {
|
||||
@@ -45,27 +34,56 @@ public class Gemini {
|
||||
}
|
||||
|
||||
public void fazerPergunta(String promptUtilizador, GeminiCallback callback) {
|
||||
Content conteudo = new Content.Builder()
|
||||
.addText(promptUtilizador)
|
||||
.build();
|
||||
try {
|
||||
JSONObject jsonBody = new JSONObject();
|
||||
JSONArray contents = new JSONArray();
|
||||
JSONObject content = new JSONObject();
|
||||
JSONArray parts = new JSONArray();
|
||||
JSONObject part = new JSONObject();
|
||||
|
||||
ListenableFuture<GenerateContentResponse> respostaFuture = modelo.generateContent(conteudo);
|
||||
Executor executor = Executors.newSingleThreadExecutor();
|
||||
part.put("text", promptUtilizador);
|
||||
parts.put(part);
|
||||
content.put("parts", parts);
|
||||
contents.put(content);
|
||||
jsonBody.put("contents", contents);
|
||||
|
||||
Futures.addCallback(respostaFuture, new FutureCallback<GenerateContentResponse>() {
|
||||
@Override
|
||||
public void onSuccess(GenerateContentResponse resultado) {
|
||||
if (resultado != null && resultado.getText() != null) {
|
||||
callback.onSuccess(resultado.getText());
|
||||
} else {
|
||||
callback.onError(new Exception("Resposta vazia da IA"));
|
||||
RequestBody body = RequestBody.create(jsonBody.toString(), MediaType.parse("application/json; charset=utf-8"));
|
||||
Request request = new Request.Builder()
|
||||
.url(API_URL)
|
||||
.post(body)
|
||||
.build();
|
||||
|
||||
client.newCall(request).enqueue(new Callback() {
|
||||
@Override
|
||||
public void onFailure(Call call, IOException e) {
|
||||
mainHandler.post(() -> callback.onError(e));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Throwable t) {
|
||||
callback.onError(t);
|
||||
}
|
||||
}, executor);
|
||||
@Override
|
||||
public void onResponse(Call call, Response response) throws IOException {
|
||||
if (response.isSuccessful()) {
|
||||
try {
|
||||
String responseBody = response.body().string();
|
||||
JSONObject jsonObject = new JSONObject(responseBody);
|
||||
JSONArray candidates = jsonObject.getJSONArray("candidates");
|
||||
JSONObject firstCandidate = candidates.getJSONObject(0);
|
||||
JSONObject contentObj = firstCandidate.getJSONObject("content");
|
||||
JSONArray partsArr = contentObj.getJSONArray("parts");
|
||||
String textResult = partsArr.getJSONObject(0).getString("text");
|
||||
|
||||
mainHandler.post(() -> callback.onSuccess(textResult));
|
||||
} catch (Exception e) {
|
||||
mainHandler.post(() -> callback.onError(new Exception("Erro ao ler resposta da IA", e)));
|
||||
}
|
||||
} else {
|
||||
String errorBody = response.body() != null ? response.body().string() : "Unknown error";
|
||||
mainHandler.post(() -> callback.onError(new Exception("Erro da API HTTP " + response.code() + ": " + errorBody)));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
} catch (Exception e) {
|
||||
mainHandler.post(() -> callback.onError(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user