branch: elpa/gptel
commit e305e748aa906ee2306f06b5cd3c050c0c4728a6
Author: Karthik Chikmagalur <karthikchikmaga...@gmail.com>
Commit: Karthik Chikmagalur <karthikchikmaga...@gmail.com>

    gptel-openai: Fix JSON encoding for function args when parsing
    
    Tool call arguments are supplied to and by OpenAI as a JSON
    object.  When reading tool call args/results from the buffer,
    gptel ends up JSON encoding the args twice: once to get results as
    a JSON object, and once again when sending it.  Non-ascii UTF-8
    chars are encoded to codepoints, and attempting to JSON-encode
    these codepoints again causes the request to fail.  Fix by
    decoding the args to UTF-8 after the first encoding.
    (#1001 and #1004)
    
    * gptel-openai.el (gptel--parse-list, gptel--parse-buffer): Decode
    the JSON encoded tool args (as read from a chat buffer) to UTF-8.
---
 gptel-openai.el | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

diff --git a/gptel-openai.el b/gptel-openai.el
index 79bed587dd5..ed72db0d075 100644
--- a/gptel-openai.el
+++ b/gptel-openai.el
@@ -391,7 +391,9 @@ If the ID has the format used by a different backend, use 
as-is."
                 (list :type "function"
                       :id (plist-get call :id)
                       :function `( :name ,(plist-get call :name)
-                                   :arguments ,(gptel--json-encode (plist-get 
call :args))))))
+                                   :arguments ,(decode-coding-string
+                                                (gptel--json-encode (plist-get 
call :args))
+                                                'utf-8 t)))))
               full-prompt)
              (push (car (gptel--parse-tool-results backend (list (cdr 
entry)))) full-prompt))))
         (nreverse full-prompt))
@@ -417,7 +419,10 @@ If the ID has the format used by a different backend, use 
as-is."
                (condition-case nil
                    (let* ((tool-call (read (current-buffer)))
                           (name (plist-get tool-call :name))
-                          (arguments (gptel--json-encode (plist-get tool-call 
:args))))
+                          (arguments (decode-coding-string
+                                      (gptel--json-encode (plist-get tool-call 
:args))
+                                      'utf-8 t)))
+                     (setq id (gptel--openai-format-tool-id id))
                      (plist-put tool-call :id id)
                      (plist-put tool-call :result
                                 (string-trim (buffer-substring-no-properties

Reply via email to