Skip to content

Commit f6194af

Browse files
authored
Merge pull request #16 from sollarp/main
Fixes unwanted string '/n'
2 parents cf20d6a + d12739e commit f6194af

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

app/src/main/java/com/chatgptlite/wanted/data/remote/OpenAIRepositoryImpl.kt

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,10 @@ class OpenAIRepositoryImpl @Inject constructor(
2121
override fun textCompletionsWithStream(params: TextCompletionsParam): Flow<String> =
2222
callbackFlow {
2323
withContext(Dispatchers.IO) {
24-
val response = (if (params.isChatCompletions) openAIApi.textCompletionsTurboWithStream(
25-
params.toJson()
26-
) else openAIApi.textCompletionsWithStream(params.toJson())).execute()
24+
val response =
25+
(if (params.isChatCompletions) openAIApi.textCompletionsTurboWithStream(
26+
params.toJson()
27+
) else openAIApi.textCompletionsWithStream(params.toJson())).execute()
2728

2829
if (response.isSuccessful) {
2930
val input = response.body()?.byteStream()?.bufferedReader() ?: throw Exception()
@@ -38,7 +39,9 @@ class OpenAIRepositoryImpl @Inject constructor(
3839
try {
3940
// Handle & convert data -> emit to client
4041
val value =
41-
if (params.isChatCompletions) lookupDataFromResponseTurbo(line) else lookupDataFromResponse(
42+
if (params.isChatCompletions) lookupDataFromResponseTurbo(
43+
line
44+
) else lookupDataFromResponse(
4245
line
4346
)
4447

@@ -79,13 +82,18 @@ class OpenAIRepositoryImpl @Inject constructor(
7982

8083
close()
8184
}
82-
85+
/** Replace any double newline characters (\n\n) with a space.
86+
Replace any single newline characters (\n) with a space.
87+
*/
8388
private fun lookupDataFromResponse(jsonString: String): String {
8489
val regex = """"text"\s*:\s*"([^"]+)"""".toRegex()
8590
val matchResult = regex.find(jsonString)
8691

8792
if (matchResult != null && matchResult.groupValues.size > 1) {
88-
return matchResult.groupValues[1]
93+
val extractedText = matchResult.groupValues[1]
94+
return extractedText
95+
.replace("\\n\\n", " ")
96+
.replace("\\n", " ")
8997
}
9098

9199
return " "
@@ -96,7 +104,10 @@ class OpenAIRepositoryImpl @Inject constructor(
96104
val matchResult = regex.find(jsonString)
97105

98106
if (matchResult != null && matchResult.groupValues.size > 1) {
99-
return matchResult.groupValues[1]
107+
val extractedText = matchResult.groupValues[1]
108+
return extractedText
109+
.replace("\\n\\n", " ")
110+
.replace("\\n", " ")
100111
}
101112

102113
return " "

0 commit comments

Comments
 (0)