| 76 | } |
| 77 | |
| 78 | static void checkModeration(Context context, String text) throws JSONException, IOException { |
| 79 | // https://platform.openai.com/docs/api-reference/moderations/create |
| 80 | JSONObject jrequest = new JSONObject(); |
| 81 | jrequest.put("input", text); |
| 82 | JSONObject jresponse = call(context, "POST", "moderations", jrequest); |
| 83 | JSONArray jresults = jresponse.getJSONArray("results"); |
| 84 | for (int i = 0; i < jresults.length(); i++) { |
| 85 | JSONObject jresult = jresults.getJSONObject(i); |
| 86 | if (jresult.getBoolean("flagged")) { |
| 87 | List<String> violations = new ArrayList<>(); |
| 88 | JSONObject jcategories = jresult.getJSONObject("categories"); |
| 89 | JSONObject jcategory_scores = jresult.getJSONObject("category_scores"); |
| 90 | Iterator<String> keys = jcategories.keys(); |
| 91 | while (keys.hasNext()) { |
| 92 | String key = keys.next(); |
| 93 | Object value = jcategories.get(key); |
| 94 | if (Boolean.TRUE.equals(value)) { |
| 95 | Double score = (jcategories.has(key) ? jcategory_scores.getDouble(key) : null); |
| 96 | violations.add(key + (score == null ? "" : ":" + Math.round(score * 100) + "%")); |
| 97 | } |
| 98 | } |
| 99 | throw new IllegalArgumentException(TextUtils.join(", ", violations)); |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | static double[] getEmbedding(Context context, String text, String model) throws JSONException, IOException { |
| 105 | // https://platform.openai.com/docs/api-reference/embeddings |