1
0
Fork 0

First attempt to improve error handling whenever FastGPT returns error output

This commit is contained in:
Bram Schoenmakers 2024-04-05 22:53:05 +02:00
parent af03f7d1f8
commit e4200270c0
Signed by: bram
GPG key ID: 0CCD19DFDC63258F
2 changed files with 24 additions and 5 deletions

View file

@ -52,6 +52,13 @@ TEXT is the output text, optionally with a list of REFERENCES."
(when references
(list (cons "references" references))))))))
(defun kagi-test--error-output (&optional msg)
"Construct a fictitious erroneous result from the Kagi FastGPT API."
(json-encode
(list `(data . ((output . nil)
(error . (((code . 42)
(msg . ,(or msg "Too bad"))))))))))
(buttercup-define-matcher-for-binary-function
:to-be-equal-including-properties equal-including-properties
:expect-match-phrase "Expected `%A' to be equal (incl. properties) to %b, but `%A' was %a."
@ -151,7 +158,14 @@ https://www.example.com"
(expect #'kagi--fastgpt-display-result :to-have-been-called))
(it "makes exactly one API call"
(kagi-fastgpt-prompt "foo")
(expect #'kagi--call-api :to-have-been-called-times 1)))
(expect #'kagi--call-api :to-have-been-called-times 1))
(it "handles empty output and returned errors from the API gracefully"
(spy-on #'kagi--call-api :and-return-value (kagi-test--error-output))
(spy-on #'kagi--fastgpt :and-call-through)
(expect (kagi-fastgpt-prompt "foo") :to-throw)
(expect (spy-context-thrown-signal
(spy-calls-most-recent #'kagi--fastgpt))
:to-equal '(error "Too bad (42)"))))
(describe "kagi-translate"
(before-each
(spy-on #'kagi-fastgpt-prompt))

13
kagi.el
View file

@ -346,10 +346,15 @@ retrieving a result from Lisp code."
(parsed-response (json-parse-string response))
(output (kagi--gethash parsed-response "data" "output"))
(references (kagi--gethash parsed-response "data" "references")))
(string-trim
(format "%s\n\n%s"
(kagi--format-output output)
(kagi--format-references references)))))
(if output
(string-trim (format "%s\n\n%s"
(kagi--format-output output)
(kagi--format-references references)))
(if-let ((firsterror (aref (kagi--gethash parsed-response "error") 0)))
(error (format "%s (%s)"
(gethash "msg" firsterror)
(gethash "code" firsterror)))
(error "An error occurred while querying FastGPT")))))
(defun kagi--fastgpt-display-result (result)
"Display the RESULT of a FastGPT prompt in a new buffer."