Skip to content

Commit

Permalink
feat: GPT请求支持设置超时
Browse files Browse the repository at this point in the history
  • Loading branch information
jing332 committed Jul 24, 2023
1 parent 7a77623 commit 17cd779
Show file tree
Hide file tree
Showing 9 changed files with 178 additions and 24 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.github.jing332.text_searcher.const

object ConfigConst {
const val KEY_GPT_SOCKET_TIMEOUT = "gpt_socket_timeout"
const val KEY_IS_WINDOW_FULL_SCREEN = "is_window_full_screen"
const val KEY_LAST_SOURCE_ID = "last_source_id"
const val KEY_FONT_DIR = "font_dir"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ object AppConfig {
initialValue = false
)

var gptSocketTimeout = mutableDataSaverStateOf(
dataSaverInterface = dataSaverPref,
key = ConfigConst.KEY_GPT_SOCKET_TIMEOUT,
initialValue = 8L
)

fun fillDefaultValues(context: Context) {
// if (systemPrompt.value.isEmpty())
// systemPrompt.value = context.getString(R.string.gpt_system_prompt)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
package com.github.jing332.text_searcher.help

object OpenAIHelper {
import com.aallam.openai.api.http.Timeout
import com.aallam.openai.api.logging.LogLevel
import com.aallam.openai.api.logging.Logger
import com.aallam.openai.client.LoggingConfig
import com.aallam.openai.client.OpenAIConfig
import com.aallam.openai.client.RetryStrategy
import kotlin.time.Duration.Companion.milliseconds

object OpenAIHelper {
fun openAiConfig(token: String): OpenAIConfig {
return OpenAIConfig(
token = token,
timeout = Timeout(socket = AppConfig.gptSocketTimeout.value.milliseconds),
retry = RetryStrategy(0),
logging = LoggingConfig(logger = Logger.Empty, logLevel = LogLevel.None),
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
Expand All @@ -17,24 +19,30 @@ import androidx.compose.material3.IconButton
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.github.jing332.text_searcher.R
import com.github.jing332.text_searcher.help.AppConfig
import com.github.jing332.text_searcher.ui.LocalNavController
import com.github.jing332.text_searcher.ui.widgets.LabelSlider
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
Expand Down Expand Up @@ -77,6 +85,23 @@ private fun ContentScreen(modifier: Modifier) {
isDialogFullScreen = it
}
)


var gptSocketTimeout by remember { AppConfig.gptSocketTimeout }
PreferenceSlider(
title = { Text(stringResource(R.string.gpt_timeout)) },
subTitle = { Text(stringResource(R.string.gpt_timeout_msg)) },
value = gptSocketTimeout.toFloat(),
onValueChange = {
gptSocketTimeout = it.toLong()
},
valueRange = 2f..30f,
steps = 29,
) {
Row {
Text("${gptSocketTimeout}s")
}
}
}
}

Expand Down Expand Up @@ -117,6 +142,123 @@ private fun PreferenceSwitch(
}
}

@Composable
fun BasePreferenceWidget(
modifier: Modifier = Modifier,
onClick: () -> Unit,
title: @Composable () -> Unit,
subTitle: @Composable () -> Unit,
content: @Composable RowScope.() -> Unit,
) {
Row(modifier = modifier
.minimumInteractiveComponentSize()
.clip(MaterialTheme.shapes.extraSmall)
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = rememberRipple()
) {
onClick()
}
.padding(8.dp)
) {
Column(
Modifier
.weight(1f)
.align(Alignment.CenterVertically)
) {
CompositionLocalProvider(LocalTextStyle provides MaterialTheme.typography.titleMedium) {
title()
}

CompositionLocalProvider(LocalTextStyle provides MaterialTheme.typography.titleSmall) {
subTitle()
}
}

Row(Modifier.align(Alignment.CenterVertically)) {
content()
}
}
}

@Composable
private fun PreferenceSlider(
title: @Composable () -> Unit,
subTitle: @Composable () -> Unit,
value: Float,
onValueChange: (Float) -> Unit,
valueRange: ClosedFloatingPointRange<Float> = 0f..1f,
steps: Int = 0,
label: @Composable (title: @Composable () -> Unit) -> Unit,
) {
PreferenceDialog(title = title, subTitle = subTitle, dialogContent = {
LabelSlider(
value = value,
onValueChange = onValueChange,
valueRange = valueRange,
steps = steps
) {
label(title)
}
},
endContent = {
label(title)
}
)
}

@Preview
@Composable
fun PreferenceSliderPreview() {
MaterialTheme {
var v by remember { mutableFloatStateOf(0.5f) }
PreferenceSlider(
title = { Text("title") },
subTitle = { Text("subTitle") },
value = v,
onValueChange = { v = it },
label = {
Row {
it()
Text(text = ": $v")
}
}
)
}
}

@Composable
private fun PreferenceDialog(
modifier: Modifier = Modifier,
title: @Composable () -> Unit,
subTitle: @Composable () -> Unit,

dialogContent: @Composable ColumnScope.() -> Unit,
endContent: @Composable RowScope.() -> Unit = {},
) {
var showDialog by remember { mutableStateOf(false) }
if (showDialog) {
Dialog(onDismissRequest = { showDialog = false }) {
Surface(
modifier = Modifier.fillMaxWidth(),
tonalElevation = 4.dp,
shape = MaterialTheme.shapes.small,
) {
Column(Modifier.padding(8.dp)) {
title()
dialogContent()
}
}
}
}
BasePreferenceWidget(modifier, onClick = {
showDialog = true
}, title = title, subTitle = subTitle) {
endContent()
}
}


@Preview
@Composable
fun ContentPreview() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ private fun TextStyleSettingsScreen(
) {
Text(
stringResource(
R.string.labe_vertical_margin,
R.string.label_vertical_margin,
String.format("%.1f", verticalMargin)
)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,10 @@ import com.aallam.openai.api.BetaOpenAI
import com.aallam.openai.api.chat.ChatCompletionRequest
import com.aallam.openai.api.chat.ChatMessage
import com.aallam.openai.api.chat.ChatRole
import com.aallam.openai.api.logging.LogLevel
import com.aallam.openai.api.logging.Logger
import com.aallam.openai.api.model.ModelId
import com.aallam.openai.client.LoggingConfig
import com.aallam.openai.client.OpenAI
import com.aallam.openai.client.RetryStrategy
import com.github.jing332.text_searcher.help.LocalTtsEngineHelper
import com.github.jing332.text_searcher.help.OpenAIHelper
import kotlinx.coroutines.isActive
import kotlin.coroutines.coroutineContext

Expand All @@ -37,13 +34,7 @@ class GptSearchScreenViewModel : ViewModel() {
systemPrompt: String,
model: String
) {
val openAI = OpenAI(
token = token,
retry = RetryStrategy(0),
logging = LoggingConfig(logger = Logger.Empty, logLevel = LogLevel.None)
//timeout = Timeout(request = 8.seconds, connect = 8.seconds, socket = 8.seconds),
// proxy = ProxyConfig.Http("http://127.0.0.1:10801")
)
val openAI = OpenAI(OpenAIHelper.openAiConfig(token))
val chatCompletionRequest = ChatCompletionRequest(
model = ModelId(model),
messages = listOf(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,9 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.aallam.openai.api.exception.OpenAIAPIException
import com.aallam.openai.api.exception.OpenAIException
import com.aallam.openai.api.logging.Logger
import com.aallam.openai.client.LoggingConfig
import com.aallam.openai.client.OpenAI
import com.aallam.openai.client.RetryStrategy
import com.github.jing332.text_searcher.R
import com.github.jing332.text_searcher.help.OpenAIHelper

class ModelSelectionViewModel : ViewModel() {
var models by mutableStateOf(listOf<String>())
Expand All @@ -23,9 +19,8 @@ class ModelSelectionViewModel : ViewModel() {
throw Exception(context.getString(R.string.error_open_ai_api_key_empty))
}

val openAi =
OpenAI(token, retry = RetryStrategy(1), logging = LoggingConfig(logger = Logger.Empty))
val openAI = OpenAI(OpenAIHelper.openAiConfig(token))
models =
openAi.models().filter { it.id.id.contains("gpt-") }.map { it.id.id }.sortedBy { it }
openAI.models().filter { it.id.id.contains("gpt-") }.map { it.id.id }.sortedBy { it }
}
}
6 changes: 4 additions & 2 deletions app/src/main/res/values-en/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@
<string name="preference">Preferences</string>
<string name="search_windows_full_screen">Search window full screen</string>
<string name="search_window_full_screen_msg">When enabled, the search window will cancel the horizontal margin to be full screen.</string>
<string name="label_horizontal_margin">水平边距:%1$sdp</string>
<string name="labe_vertical_margin">垂直边距:%1$sdp</string>
<string name="label_horizontal_margin">Horizontal Margin:%1$sdp</string>
<string name="label_vertical_margin">Vertical Margin: %1$sdp</string>
<string name="gpt_timeout">ChatGPT Timeout</string>
<string name="gpt_timeout_msg">The request will be canceled after the set time without response</string>
</resources>
4 changes: 3 additions & 1 deletion app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,7 @@
<string name="search_windows_full_screen">搜索窗口全屏</string>
<string name="search_window_full_screen_msg">开启后,搜索窗口将取消水平边距以全屏。</string>
<string name="label_horizontal_margin">水平边距:%1$sdp</string>
<string name="labe_vertical_margin">垂直边距:%1$sdp</string>
<string name="label_vertical_margin">垂直边距:%1$sdp</string>
<string name="gpt_timeout">ChatGPT 超时</string>
<string name="gpt_timeout_msg">超过设定时间未响应后将取消请求</string>
</resources>

0 comments on commit 17cd779

Please sign in to comment.