Skip to content

Commit

Permalink
fix: do not break on newlines on function returns (#864)
Browse files Browse the repository at this point in the history
Signed-off-by: Ettore Di Giacinto <[email protected]>
  • Loading branch information
mudler authored Aug 4, 2023
1 parent 4aa5dac commit acd829a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
3 changes: 3 additions & 0 deletions api/openai/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/go-skynet/LocalAI/api/options"
"github.com/go-skynet/LocalAI/pkg/grammar"
model "github.com/go-skynet/LocalAI/pkg/model"
"github.com/go-skynet/LocalAI/pkg/utils"
"github.com/gofiber/fiber/v2"
"github.com/rs/zerolog/log"
"github.com/valyala/fasthttp"
Expand Down Expand Up @@ -274,6 +275,8 @@ func ChatEndpoint(cm *config.ConfigLoader, o *options.Option) func(c *fiber.Ctx)
if processFunctions {
// As we have to change the result before processing, we can't stream the answer (yet?)
ss := map[string]interface{}{}
// This prevent newlines to break JSON parsing for clients
s = utils.EscapeNewLines(s)
json.Unmarshal([]byte(s), &ss)
log.Debug().Msgf("Function return: %s %+v", s, ss)

Expand Down
13 changes: 13 additions & 0 deletions pkg/utils/json.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package utils

import "regexp"

var matchNewlines = regexp.MustCompile(`[\r\n]`)

const doubleQuote = `"[^"\\]*(?:\\[\s\S][^"\\]*)*"`

func EscapeNewLines(s string) string {
return regexp.MustCompile(doubleQuote).ReplaceAllStringFunc(s, func(s string) string {
return matchNewlines.ReplaceAllString(s, "\\n")
})
}

0 comments on commit acd829a

Please sign in to comment.