Skip to content

Commit

Permalink
fix: http post android unhandled exception
Browse files Browse the repository at this point in the history
  • Loading branch information
popoway committed Mar 4, 2024
1 parent 4cefc3e commit 002bf46
Show file tree
Hide file tree
Showing 12 changed files with 227 additions and 195 deletions.
5 changes: 4 additions & 1 deletion android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ android {
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true
}

signingConfigs {
Expand All @@ -78,4 +79,6 @@ flutter {
source '../..'
}

dependencies {}
dependencies {
implementation 'com.android.support:multidex:2.0.1' //enter the latest multidex version
}
3 changes: 2 additions & 1 deletion android/app/src/debug/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
1 change: 1 addition & 0 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Include only if your app benefits from precise location access. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Expand Down
3 changes: 2 additions & 1 deletion android/app/src/profile/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
1 change: 1 addition & 0 deletions assets/flutter_i18n/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ chat:
disclaimer: "ChatKnights can make mistakes. Consider checking important information."
placeholder: "Message ChatKnights..."
too-short: "Your message is too short for me to understand. Please elaborate your question."
error: "Sorry, I am not able to answer your question at the moment. Please try again later."

map:
hint: "Search buildings..."
Expand Down
1 change: 1 addition & 0 deletions assets/flutter_i18n/es.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ chat:
disclaimer: "ChatKnights puede cometer errores. Considera verificar información importante."
placeholder: "Mensaje a ChatKnights..."
too-short: "Tu mensaje es demasiado corto para que yo lo entienda. Por favor, elabora tu pregunta."
error: "Lo siento, no puedo responder a eso. Por favor, intenta otra pregunta."

map:
hint: "Buscar edificios..."
Expand Down
1 change: 1 addition & 0 deletions assets/flutter_i18n/he.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ chat:
disclaimer: "ל-ChatKnights יכולים להיות טעויות. שקול לבדוק מידע חשוב."
placeholder: "שלח הודעה ל-ChatKnights..."
too-short: "ההודעה שלך קצרה מכדי שאוכל להבין. אנא פרט את שאלתך."
error: "אוי! נראה שיש בעיה עם התשובה שלי. אנא נסה שוב."

map:
hint: "חפש בניינים..."
Expand Down
1 change: 1 addition & 0 deletions assets/flutter_i18n/hi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ chat:
disclaimer: "ChatKnights गलतियाँ कर सकता है। महत्वपूर्ण जानकारी की जाँच करने पर विचार करें।"
placeholder: "ChatKnights को संदेश भेजें..."
too-short: "आपका संदेश मेरे समझने के लिए बहुत छोटा है। कृपया अपना प्रश्न विस्तृत करें।"
error: "क्षमा करें, मैं आपके प्रश्न का जवाब नहीं दे सकता। कृपया दोबारा प्रयास करें।"

map:
hint: "भवनों की खोज करें..."
Expand Down
1 change: 1 addition & 0 deletions assets/flutter_i18n/zh.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ chat:
disclaimer: "ChatKnights 可能会犯错误。请考虑核对重要信息。"
placeholder: "给 ChatKnights 发消息..."
too-short: "您的信息太短了,我无法理解。请详细说明您的问题。"
error: "哎呀!看起来我的回答出了问题。请再试一次。"

map:
hint: "搜索建筑物..."
Expand Down
47 changes: 30 additions & 17 deletions lib/chatknights.dart
Original file line number Diff line number Diff line change
Expand Up @@ -242,16 +242,22 @@ class _MyChatPageState extends State<MyChatPage> {
});
}

Future<http.Response> fetchCompletion(String partialRequest) {
Future<http.Response> fetchCompletion(String partialRequest) async {
print(partialRequest);
return http.post(
Uri.parse(
"https://$_endpoint/openai/deployments/$_model/chat/completions?api-version=2023-12-01-preview"),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'api-key': _key,
},
body: partialRequest);
try {
return await http.post(
Uri.parse(
"https://$_endpoint/openai/deployments/$_model/chat/completions?api-version=2023-12-01-preview"),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'api-key': _key,
},
body: partialRequest);
} catch (e) {
print('Exception caught: $e');
// Handle the exception here
}
return Future.value(http.Response('{"error": "Exception caught"}', 500));
}

/// Composes request JSON for Azure OpenAI API
Expand Down Expand Up @@ -363,14 +369,21 @@ class _MyChatPageState extends State<MyChatPage> {
_replaceMessage(textMessage2);

// send message to Azure OpenAI API
var response = await fetchCompletion(
await _composeRequestJSON(_messages, message.text));
print(utf8.decode(response.bodyBytes));
var responseJSON = jsonDecode(utf8.decode(response.bodyBytes));
// sample response:
// {"id":"chatcmpl-8f6aKXU20mj0koJvwLXLe9eb9Qynw","object":"chat.completion","created":1704807452,"model":"gpt-35-turbo","choices":[{"finish_reason":"stop","index":0,"message":{"role":"assistant","content":"Yes, many Azure AI services support customer managed keys. These include Azure Cognitive Services, Azure Machine Learning, and Azure Databricks."}}],"usage":{"prompt_tokens":59,"completion_tokens":27,"total_tokens":86}}
var responseContent = responseJSON['choices'][0]['message']['content'];

http.Response response;
String responseContent = "Error: No response.";
try {
response = await fetchCompletion(
await _composeRequestJSON(_messages, message.text));
print(utf8.decode(response.bodyBytes));
var responseJSON = jsonDecode(utf8.decode(response.bodyBytes));
// sample response:
// {"id":"chatcmpl-8f6aKXU20mj0koJvwLXLe9eb9Qynw","object":"chat.completion","created":1704807452,"model":"gpt-35-turbo","choices":[{"finish_reason":"stop","index":0,"message":{"role":"assistant","content":"Yes, many Azure AI services support customer managed keys. These include Azure Cognitive Services, Azure Machine Learning, and Azure Databricks."}}],"usage":{"prompt_tokens":59,"completion_tokens":27,"total_tokens":86}}
responseContent = responseJSON['choices'][0]['message']['content'];
} catch (e) {
print('Exception caught: $e');
responseContent = FlutterI18n.translate(context, "chat.error");
// Handle the exception here
}
var responseMessage = types.TextMessage(
author: _bot,
createdAt: DateTime.now().millisecondsSinceEpoch,
Expand Down
Loading

0 comments on commit 002bf46

Please sign in to comment.