Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit acd829a

Browse files
authoredAug 4, 2023
fix: do not break on newlines on function returns (mudler#864)
Signed-off-by: Ettore Di Giacinto <mudler@localai.io>
1 parent 4aa5dac commit acd829a

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed
 

‎api/openai/chat.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"github.com/go-skynet/LocalAI/api/options"
1313
"github.com/go-skynet/LocalAI/pkg/grammar"
1414
model "github.com/go-skynet/LocalAI/pkg/model"
15+
"github.com/go-skynet/LocalAI/pkg/utils"
1516
"github.com/gofiber/fiber/v2"
1617
"github.com/rs/zerolog/log"
1718
"github.com/valyala/fasthttp"
@@ -274,6 +275,8 @@ func ChatEndpoint(cm *config.ConfigLoader, o *options.Option) func(c *fiber.Ctx)
274275
if processFunctions {
275276
// As we have to change the result before processing, we can't stream the answer (yet?)
276277
ss := map[string]interface{}{}
278+
// This prevent newlines to break JSON parsing for clients
279+
s = utils.EscapeNewLines(s)
277280
json.Unmarshal([]byte(s), &ss)
278281
log.Debug().Msgf("Function return: %s %+v", s, ss)
279282

‎pkg/utils/json.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package utils
2+
3+
import "regexp"
4+
5+
var matchNewlines = regexp.MustCompile(`[\r\n]`)
6+
7+
const doubleQuote = `"[^"\\]*(?:\\[\s\S][^"\\]*)*"`
8+
9+
func EscapeNewLines(s string) string {
10+
return regexp.MustCompile(doubleQuote).ReplaceAllStringFunc(s, func(s string) string {
11+
return matchNewlines.ReplaceAllString(s, "\\n")
12+
})
13+
}

0 commit comments

Comments
 (0)
Failed to load comments.