@@ -21,9 +21,10 @@ class OpenAIRepositoryImpl @Inject constructor(
21
21
override fun textCompletionsWithStream (params : TextCompletionsParam ): Flow <String > =
22
22
callbackFlow {
23
23
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()
27
28
28
29
if (response.isSuccessful) {
29
30
val input = response.body()?.byteStream()?.bufferedReader() ? : throw Exception ()
@@ -38,7 +39,9 @@ class OpenAIRepositoryImpl @Inject constructor(
38
39
try {
39
40
// Handle & convert data -> emit to client
40
41
val value =
41
- if (params.isChatCompletions) lookupDataFromResponseTurbo(line) else lookupDataFromResponse(
42
+ if (params.isChatCompletions) lookupDataFromResponseTurbo(
43
+ line
44
+ ) else lookupDataFromResponse(
42
45
line
43
46
)
44
47
@@ -79,13 +82,18 @@ class OpenAIRepositoryImpl @Inject constructor(
79
82
80
83
close()
81
84
}
82
-
85
+ /* * Replace any double newline characters (\n\n) with a space.
86
+ Replace any single newline characters (\n) with a space.
87
+ */
83
88
private fun lookupDataFromResponse (jsonString : String ): String {
84
89
val regex = """ "text"\s*:\s*"([^"]+)"""" .toRegex()
85
90
val matchResult = regex.find(jsonString)
86
91
87
92
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" , " " )
89
97
}
90
98
91
99
return " "
@@ -96,7 +104,10 @@ class OpenAIRepositoryImpl @Inject constructor(
96
104
val matchResult = regex.find(jsonString)
97
105
98
106
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" , " " )
100
111
}
101
112
102
113
return " "
0 commit comments