(Context context, String method, String path, JSONObject args)
| 173 | } |
| 174 | |
| 175 | private static JSONObject call(Context context, String method, String path, JSONObject args) throws JSONException, IOException { |
| 176 | SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); |
| 177 | String apikey = prefs.getString("openai_apikey", null); |
| 178 | |
| 179 | // https://platform.openai.com/docs/api-reference/introduction |
| 180 | Uri uri = Uri.parse(getUri(context)).buildUpon().appendEncodedPath(path).build(); |
| 181 | Log.i("OpenAI uri=" + uri); |
| 182 | |
| 183 | long start = new Date().getTime(); |
| 184 | |
| 185 | URL url = new URL(uri.toString()); |
| 186 | HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
| 187 | |
| 188 | connection.setRequestMethod(method); |
| 189 | connection.setDoOutput(args != null); |
| 190 | connection.setDoInput(true); |
| 191 | connection.setReadTimeout(TIMEOUT * 1000); |
| 192 | connection.setConnectTimeout(TIMEOUT * 1000); |
| 193 | ConnectionHelper.setUserAgent(context, connection); |
| 194 | connection.setRequestProperty("Accept", "application/json"); |
| 195 | connection.setRequestProperty("Content-Type", "application/json"); |
| 196 | connection.setRequestProperty("Authorization", "Bearer " + apikey); |
| 197 | connection.connect(); |
| 198 | |
| 199 | try { |
| 200 | if (args != null) { |
| 201 | String json = args.toString(); |
| 202 | Log.i("OpenAI request=" + json); |
| 203 | connection.getOutputStream().write(json.getBytes()); |
| 204 | } |
| 205 | |
| 206 | int status = connection.getResponseCode(); |
| 207 | if (status != HttpURLConnection.HTTP_OK) { |
| 208 | String error = "Error " + status + ": " + connection.getResponseMessage(); |
| 209 | String detail = null; |
| 210 | try { |
| 211 | // HTTP 429 |
| 212 | // { |
| 213 | // "error": { |
| 214 | // "message": "You exceeded your current quota, please check your plan and billing details.", |
| 215 | // "type": "insufficient_quota", |
| 216 | // "param": null, |
| 217 | // "code": null |
| 218 | // } |
| 219 | //} |
| 220 | InputStream is = connection.getErrorStream(); |
| 221 | if (is != null) |
| 222 | detail = Helper.readStream(is); |
| 223 | } catch (Throwable ex) { |
| 224 | Log.w(ex); |
| 225 | } |
| 226 | Log.w("OpenAI error=" + error + " detail=" + detail); |
| 227 | if (detail != null) |
| 228 | try { |
| 229 | JSONObject jroot = new JSONObject(detail); |
| 230 | JSONObject jerror = jroot.optJSONObject("error"); |
| 231 | if (jerror != null) { |
| 232 | String msg = jerror.optString("message"); |
no test coverage detected