1
0
Fork 0

Refactor code around the curl call

This makes passing input data and setting flags more robust.
This commit is contained in:
Bram Schoenmakers 2023-12-24 23:18:57 +01:00
parent 0105a07695
commit 11865f92cf
Signed by: bram
GPG key ID: 0CCD19DFDC63258F

46
kagi.el
View file

@ -77,22 +77,17 @@ https://kagi.com/settings?p=api"
:type 'boolean :type 'boolean
:group 'kagi) :group 'kagi)
(defun kagi--build-curl-command (prompt) (defun kagi--curl-flags ()
"Build a `curl' command to call the Kagi FastGPT API. "Collect flags for a `curl' command to call the Kagi FastGPT API."
(let ((token (cond ((functionp kagi-api-token) (funcall kagi-api-token))
PROMPT is used to fill in the POST part of the request." ((stringp kagi-api-token) kagi-api-token)
(let* ((input-obj `((query . ,prompt))) (t (error "No API token configured in variable kagi-api-token")))))
(data (json-encode input-obj)) `("--silent"
(token (cond ((functionp kagi-api-token) (funcall kagi-api-token)) "--header" ,(format "Authorization: Bot %s" token)
((stringp kagi-api-token) kagi-api-token) "--header" "Content-Type: application/json"
(t (error "No API token configured in variable kagi-api-token")))) "--data" "@-"
(curl-flags `("--silent" ,kagi-api-fastgpt-url
,(format "--header \"Authorization: Bot %s\"" token) )))
"--header \"Content-Type: application/json\""
,(format "--data '%s'" data))))
(format "curl %s %s"
(string-join curl-flags " ")
kagi-api-fastgpt-url)))
(defun kagi--html-bold-to-face (string) (defun kagi--html-bold-to-face (string)
"Convert HTML tags inside STRING to faces. "Convert HTML tags inside STRING to faces.
@ -148,15 +143,18 @@ PROMPT is used to fill in the POST part of the request."
`kagi--canned-response', no remote call will be made. This is useful `kagi--canned-response', no remote call will be made. This is useful
for development purposes as API calls require a charge your API for development purposes as API calls require a charge your API
credit at Kagi." credit at Kagi."
(let ((command (kagi--build-curl-command prompt))) (if kagi-debug
(if kagi-debug kagi--canned-response
kagi--canned-response
(with-temp-buffer (with-temp-buffer
(let ((return (call-process-shell-command command nil t))) (insert (json-encode `((query . ,prompt))))
(if (eql return 0) (let* ((call-process-flags '(nil nil "curl" t t nil))
(buffer-string) (curl-flags (kagi--curl-flags))
(error "Call to FastGPT API returned with status %s" return))))))) (all-flags (append call-process-flags curl-flags))
(return (apply #'call-process-region all-flags)))
(if (eql return 0)
(buffer-string)
(error "Call to FastGPT API returned with status %s" return))))))
(defun kagi--process-prompt (prompt) (defun kagi--process-prompt (prompt)
"Submit a PROMPT to FastGPT and process the API response. "Submit a PROMPT to FastGPT and process the API response.