Hello
- User
Hello
- Assistant
Hi there! How can I assist you today?
- User
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Hello
Hi there! How can I assist you today?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Please fix this code and make it functional: package com.hx.chathx
import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.hx.chathx.ui.theme.ChatHXTheme
class MainActivity : ComponentActivity() {
private val gson = Gson()
private val client = OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS)
.build()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ChatHXTheme { // Use the app's theme
ChatScreen()
}
}
}
}
@Composable fun ChatScreen() { val messages = remember { mutableStateListOf() } var userInput by remember { mutableStateOf("") } val isLoading = remember { mutableStateOf(false) }
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Bottom
) {
// Chat Message Area
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.weight(1f),
contentPadding = PaddingValues(16.dp)
) {
items(messages) { message ->
MessageCard(message)
}
}
// User Input Area
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
OutlinedTextField(
value = userInput,
onValueChange = { userInput = it },
label = { Text("Type your question...") },
modifier = Modifier
.weight(1f)
.padding(end = 8.dp)
)
Button(
onClick = {
sendMessage(userInput, messages, isLoading)
userInput = "" // Clear input after sending
},
modifier = Modifier.wrapContentSize(),
enabled = !isLoading.value // Disable button while loading
) {
if (isLoading.value) {
CircularProgressIndicator(color = Color.White)
} else {
Text("Send")
}
}
}
}
}
@Composable fun MessageCard(message: ChatMessage) { // Different layout for user and AI messages if (message.isUser) { Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), horizontalArrangement = Arrangement.End ) { Text( text = message.text, color = Color.White, fontWeight = FontWeight.Bold, modifier = Modifier .padding(8.dp) .background(Color.Blue) // Example user message color ) } } else { Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), horizontalArrangement = Arrangement.Start ) { Text( text = message.text, color = Color.Black, fontWeight = FontWeight.Bold, modifier = Modifier .padding(8.dp) .background(Color.LightGray) // Example AI message color ) } } }
data class ChatMessage(val text: String, val isUser: Boolean)
// Function to send message to your Flask server fun sendMessage( message: String, messages: MutableList, isLoading: MutableState ) { messages.add(ChatMessage(message, true)) isLoading.value = true
val url = "http://10.0.2.2:5000/api/chat" // Update with your Flask server URL
val requestBody = RequestBody.create(
MediaType.parse("application/json"),
gson.toJson(mapOf("message" to message))
)
val request = Request.Builder()
.url(url)
.post(requestBody)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.e("ChatHX", "Network error: ${e.message}", e)
isLoading.value = false
}
override fun onResponse(call: Call, response: Response) {
isLoading.value = false
if (response.isSuccessful) {
try {
val responseBody = response.body()?.string()
if (responseBody != null) {
val responseJson: JsonElement = gson.fromJson(responseBody, JsonElement::class.java)
val answer = responseJson.asJsonObject.get("answer").asString
val questions = responseJson.asJsonObject.get("follow_up_questions").asJsonArray
// Add AI's response
messages.add(ChatMessage(answer, false))
// Add follow-up questions
for (question in questions) {
messages.add(ChatMessage(question.asString, false))
}
} else {
Log.e("ChatHX", "Empty response body")
}
} catch (e: Exception) {
Log.e("ChatHX", "Error parsing response: ${e.message}", e)
}
} else {
Log.e("ChatHX", "Server error: ${response.code}")
}
}
})
}
@Composable fun ChatHXTheme(content: @Composable () -> Unit) { MaterialTheme( colors = darkColors( // Use dark colors as per your screenshot primary = Color(0xFF1976D2), // Example primary color, customize as needed surface = Color(0xFF121212) // Example surface color ) ) { content() } }
Certainly! There are a few issues in your code, including missing imports, improper initialization of some classes, and use of deprecated components and APIs. I'll provide a fixed and functional version of your code. It's important to ensure you have the required dependencies in your build.gradle file to make sure everything works.
Make sure you have these dependencies in your build.gradle file:
implementation 'androidx.compose.ui:ui:1.1.0'
implementation 'androidx.compose.material3:material3:1.0.0-alpha02'
implementation 'androidx.compose.ui:ui-tooling-preview:1.1.0'
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
implementation 'com.google.code.gson:gson:2.8.8'
Here is the corrected MainActivity.kt file:
package com.hx.chathx
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Button
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.google.gson.Gson
import com.google.gson.JsonElement
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.*
import java.io.IOException
import java.util.concurrent.TimeUnit
class MainActivity : ComponentActivity() {
private val gson = Gson()
private val client = OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS)
.build()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ChatHXTheme {
ChatScreen(client, gson) // Pass the OkHttpClient and Gson instance
}
}
}
}
@Composable
fun ChatScreen(client: OkHttpClient, gson: Gson) {
val messages = remember { mutableStateListOf<ChatMessage>() }
var userInput by remember { mutableStateOf("") }
val isLoading = remember { mutableStateOf(false) }
val coroutineScope = rememberCoroutineScope()
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Bottom
) {
// Chat Message Area
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.weight(1f),
contentPadding = PaddingValues(16.dp)
) {
items(messages) { message ->
MessageCard(message)
}
}
// User Input Area
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
OutlinedTextField(
value = userInput,
onValueChange = { userInput = it },
label = { Text("Type your question...") },
modifier = Modifier
.weight(1f)
.padding(end = 8.dp)
)
Button(
onClick = {
coroutineScope.launch {
sendMessage(userInput, messages, isLoading, client, gson)
userInput = ""
}
},
modifier = Modifier.wrapContentSize(),
enabled = !isLoading.value
) {
if (isLoading.value) {
CircularProgressIndicator(color = Color.White)
} else {
Text("Send")
}
}
}
}
}
@Composable
fun MessageCard(message: ChatMessage) {
// Different layout for user and AI messages
if (message.isUser) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
horizontalArrangement = Arrangement.End
) {
Text(
text = message.text,
color = Color.White,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(8.dp)
.background(Color.Blue)
)
}
} else {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
horizontalArrangement = Arrangement.Start
) {
Text(
text = message.text,
color = Color.Black,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(8.dp)
.background(Color.LightGray)
)
}
}
}
data class ChatMessage(val text: String, val isUser: Boolean)
suspend fun sendMessage(
message: String,
messages: MutableList<ChatMessage>,
isLoading: MutableState<Boolean>,
client: OkHttpClient,
gson: Gson
) {
messages.add(ChatMessage(message, true))
isLoading.value = true
val url = "http://10.0.2.2:5000/api/chat"
val requestBody = RequestBody.create(
MediaType.parse("application/json"),
gson.toJson(mapOf("message" to message))
)
val request = Request.Builder()
.url(url)
.post(requestBody)
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
Log.e("ChatHX", "Network error: ${e.message}", e)
isLoading.value = false
}
override fun onResponse(call: Call, response: Response) {
isLoading.value = false
if (response.isSuccessful) {
try {
val responseBody = response.body()?.string()
if (responseBody != null) {
val responseJson: JsonElement = gson.fromJson(responseBody, JsonElement::class.java)
val answer = responseJson.asJsonObject.get("answer").asString
val questions = responseJson.asJsonObject.get("follow_up_questions").asJsonArray
// Add AI's response
messages.add(ChatMessage(answer, false))
// Add follow-up questions
for (question in questions) {
messages.add(ChatMessage(question.asString, false))
}
} else {
Log.e("ChatHX", "Empty response body")
}
} catch (e: Exception) {
Log.e("ChatHX", "Error parsing response: ${e.message}", e)
}
} else {
Log.e("ChatHX", "Server error: ${response.code}")
}
}
})
}
@Composable
fun ChatHXTheme(content: @Composable () -> Unit) {
MaterialTheme(
colors = darkColors(
primary = Color(0xFF1976D2),
surface = Color(0xFF121212)
)
) {
content()
}
}
ChatScreen Function: Passed OkHttpClient and Gson instances to the ChatScreen.rememberCoroutineScope to launch coroutine on button click.Make sure your server is accessible at http://10.0.2.2:5000/api/chat. This address is used to connect to the local host on Android emulator which maps to localhost on host machine. If you’re testing on a real device, you might need to change this to your network IP address.
This should address the major issues and make sure the code compiles and runs properly.