diff options
author | Oscar Najera <hi@oscarnajera.com> | 2024-07-22 17:30:47 +0200 |
---|---|---|
committer | Oscar Najera <hi@oscarnajera.com> | 2024-07-27 11:51:16 +0200 |
commit | 3dabf54a58f51935f6de7a1b9a27ff3d33afb54e (patch) | |
tree | ba04277a44e3e587476a9621f44cbf4dd4181cf7 | |
parent | a1964bd9021c9aac9cff8ac074ecebe4926184ff (diff) | |
download | dotfiles-3dabf54a58f51935f6de7a1b9a27ff3d33afb54e.tar.gz dotfiles-3dabf54a58f51935f6de7a1b9a27ff3d33afb54e.tar.bz2 dotfiles-3dabf54a58f51935f6de7a1b9a27ff3d33afb54e.zip |
AI query with async request
-rw-r--r-- | elisp/ai-query.el | 34 |
1 files changed, 20 insertions, 14 deletions
diff --git a/elisp/ai-query.el b/elisp/ai-query.el index 80c9918..3bc621c 100644 --- a/elisp/ai-query.el +++ b/elisp/ai-query.el @@ -27,14 +27,8 @@ "https://gandalf.lakera.ai/api/send-message" "AI security endpoint, use it for queries.") -(defun ai-query-request (prompt) - "Query the API with this PROMPT." - (thread-first - (if (use-region-p) - (buffer-substring-no-properties (region-beginning) (region-end)) - (read-string "What is your question? ")) - (list) - (interactive)) +(defun ai-query--request (prompt callback) + "Async request to API using PROMPT and process with CALLBACK." (let ((url-request-method "POST") (url-request-extra-headers '(("Content-Type" . "application/x-www-form-urlencoded"))) @@ -43,16 +37,28 @@ (list 'prompt prompt) (cons '((defender "baseline"))) (url-build-query-string)))) + (url-retrieve ai-query-api callback))) + +(defun ai-query--process-response (_status) + "Callback function to process response." + (goto-char url-http-end-of-headers) + (let ((response (json-parse-buffer))) (with-current-buffer (get-buffer-create "*AI reply*") (markdown-mode) (erase-buffer) - (insert "# Question\n" prompt) - (insert "\n\n# Answer\n\n" - (with-current-buffer - (url-retrieve-synchronously ai-query-api) - (goto-char url-http-end-of-headers) - (gethash "answer" (json-parse-buffer)))) + (insert "# Question\n" (gethash "prompt" response)) + (insert "\n\n# Answer\n\n" (gethash "answer" response)) (display-buffer (current-buffer))))) +(defun ai-query-request (prompt) + "Query the API with this PROMPT." + (thread-first + (if (use-region-p) + (buffer-substring-no-properties (region-beginning) (region-end)) + (read-string "What is your question? ")) + (list) + (interactive)) + (ai-query--request prompt #'ai-query--process-response)) + (provide 'ai-query) ;;; ai-query.el ends here |