При получении ответа от сервера выдаёт FATAL EXCEPTION: AsyncTask #1
Выдаёт ошибку FATAL EXCEPTION: AsyncTask #1 при выполнении кода:
package su.selezzz.gptmmobile;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class GptRequest {
private final OkHttpClient client = new OkHttpClient();
private final MediaType mediaType = MediaType.parse("application/json");
public String run(String text) throws IOException {
Map<String, Object> data = new HashMap<>();
data.put("prompt", text);
data.put("temperature", 0.7);
data.put("max_tokens", 60);
data.put("top_p", 1);
data.put("frequency_penalty", 0);
data.put("presence_penalty", 0);
RequestBody body = RequestBody.create(mediaType, mapToJson(data));
Request request = new Request.Builder()
.url("https://api.openai.com/v1/engines/davinci-codex/completions")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Bearer sk-токен")
.build();
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
String[] choices = responseBody.split("\"text\": \"");
String textResponse = choices[1].split("\"")[0];
return textResponse;
}
private String mapToJson(Map<String, Object> data) {
StringBuilder builder = new StringBuilder();
builder.append("{");
for (Map.Entry<String, Object> entry : data.entrySet()) {
builder.append("\"").append(entry.getKey()).append("\":");
Object value = entry.getValue();
if (value instanceof String) {
builder.append("\"").append(value).append("\"");
} else {
builder.append(value);
}
builder.append(",");
}
builder.setCharAt(builder.length() - 1, '}');
return builder.toString();
}
}
К этому коду я обращаюсь через:
private class GptRequestTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
GptRequest request = new GptRequest();
try {
return request.run(strings[0]);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected void onPostExecute(String response) {
Log.i(TAG, "GptResponse: " + response);
// Обновление пользовательского интерфейса здесь
}
}
new GptRequestTask().execute("Hello, my name is John. What is your name?");
Вот лог:
04/22 15:56:06: Launching 'app' on Pixel 2 API 33.
Install successfully finished in 138 ms.
$ adb shell am start -n "su.selezzz.gptmmobile/su.selezzz.gptmmobile.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 15365 on device 'Pixel_2_API_33 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/ezzz.gptmmobile: Late-enabling -Xcheck:jni
W/ezzz.gptmmobile: Unexpected CPU variant for x86: x86_64.
Known variants: atom, sandybridge, silvermont, kabylake, default
W/re-initialized>: type=1400 audit(0.0:352): avc: granted { execute } for path="/data/data/su.selezzz.gptmmobile/code_cache/startup_agents/09f4021c-agent.so" dev="dm-33" ino=140011 scontext=u:r:untrusted_app:s0:c160,c256,c512,c768 tcontext=u:object_r:app_data_file:s0:c160,c256,c512,c768 tclass=file app=su.selezzz.gptmmobile
V/studio.deploy: Startup agent attached to VM
V/studio.deploy: No existing instrumentation found. Loading instrumentation from instruments-a7e44b7b.jar
W/ezzz.gptmmobile: DexFile /data/data/su.selezzz.gptmmobile/code_cache/.studio/instruments-a7e44b7b.jar is in boot class path but is not in a known location
V/studio.deploy: Applying transforms with cached classes
W/ezzz.gptmmobile: Redefining intrinsic method java.lang.Thread java.lang.Thread.currentThread(). This may cause the unexpected use of the original definition of java.lang.Thread java.lang.Thread.currentThread()in methods that have already been compiled.
W/ezzz.gptmmobile: Redefining intrinsic method boolean java.lang.Thread.interrupted(). This may cause the unexpected use of the original definition of boolean java.lang.Thread.interrupted()in methods that have already been compiled.
D/CompatibilityChangeReporter: Compat change id reported: 171979766; UID 10160; state: ENABLED
W/ziparchive: Unable to open '/data/data/su.selezzz.gptmmobile/code_cache/.overlay/base.apk/classes3.dm': No such file or directory
W/ziparchive: Unable to open '/data/app/~~BM7pT_VJEr9E5itgv4kS0Q==/su.selezzz.gptmmobile-fUJrR211N-1pXsE1XdTbFQ==/base.dm': No such file or directory
W/ziparchive: Unable to open '/data/app/~~BM7pT_VJEr9E5itgv4kS0Q==/su.selezzz.gptmmobile-fUJrR211N-1pXsE1XdTbFQ==/base.dm': No such file or directory
D/nativeloader: Configuring classloader-namespace for other apk /data/app/~~BM7pT_VJEr9E5itgv4kS0Q==/su.selezzz.gptmmobile-fUJrR211N-1pXsE1XdTbFQ==/base.apk. target_sdk_version=33, uses_libraries=, library_path=/data/app/~~BM7pT_VJEr9E5itgv4kS0Q==/su.selezzz.gptmmobile-fUJrR211N-1pXsE1XdTbFQ==/lib/x86_64, permitted_path=/data:/mnt/expand:/data/user/0/su.selezzz.gptmmobile
V/GraphicsEnvironment: ANGLE Developer option for 'su.selezzz.gptmmobile' set to: 'default'
V/GraphicsEnvironment: ANGLE GameManagerService for su.selezzz.gptmmobile: false
V/GraphicsEnvironment: Neither updatable production driver nor prerelease driver is supported.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/libEGL: loaded /vendor/lib64/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib64/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib64/egl/libGLESv2_emulation.so
D/AppCompatDelegate: Checking for metadata for AppLocalesMetadataHolderService : Service not found
W/ezzz.gptmmobile: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed)
W/ezzz.gptmmobile: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
D/CompatibilityChangeReporter: Compat change id reported: 210923482; UID 10160; state: ENABLED
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0x7488fe478550, tid 15395
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_vulkan_async_qsri ANDROID_EMU_read_color_buffer_dma GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
W/OpenGLRenderer: Failed to initialize 101010-2 format, error = EGL_SUCCESS
D/EGL_emulation: eglCreateContext: 0x7488fe4795d0: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0x7488fe4795d0: ver 2 0 (tinfo 0x748b20ab7080) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0x7488fe47a710, tid 15395
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3efffe000 size 0x2000
W/Gralloc4: allocator 4.x is not supported
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_vulkan_queue_submit_with_commands ANDROID_EMU_sync_buffer_data ANDROID_EMU_vulkan_async_qsri ANDROID_EMU_read_color_buffer_dma GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2
W/Parcel: Expecting binder but got null!
D/TrafficStats: tagSocket(94) with statsTag=0xffffffff, statsUid=-1
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: su.selezzz.gptmmobile, PID: 15365
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(AsyncTask.java:415)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:381)
at java.util.concurrent.FutureTask.setException(FutureTask.java:250)
at java.util.concurrent.FutureTask.run(FutureTask.java:269)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1137)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:637)
at java.lang.Thread.run(Thread.java:1012)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at su.selezzz.gptmmobile.GptRequest.run(GptRequest.java:37)
at su.selezzz.gptmmobile.MainActivity$GptRequestTask.doInBackground(MainActivity.java:30)
at su.selezzz.gptmmobile.MainActivity$GptRequestTask.doInBackground(MainActivity.java:24)
at android.os.AsyncTask$3.call(AsyncTask.java:394)
at java.util.concurrent.FutureTask.run(FutureTask.java:264)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1137)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:637)
at java.lang.Thread.run(Thread.java:1012)
I/Process: Sending signal. PID: 15365 SIG: 9