summaryrefslogtreecommitdiff
path: root/llm-chat-openai.el
diff options
context:
space:
mode:
Diffstat (limited to 'llm-chat-openai.el')
-rw-r--r--llm-chat-openai.el58
1 files changed, 58 insertions, 0 deletions
diff --git a/llm-chat-openai.el b/llm-chat-openai.el
new file mode 100644
index 0000000..a093dde
--- /dev/null
+++ b/llm-chat-openai.el
@@ -0,0 +1,58 @@
+;;; llm-chat-openai.el --- Implements openai llm intergration -*- lexical-binding: t; -*-
+
+;; This file is not part of GNU Emacs.
+
+;;; Code:
+
+(require 'llm-chat-api)
+
+(defvar llm-chat-openai-models '("gpt-4.1" "gpt-3.5-turbo" "gpt-5"))
+
+(cl-defgeneric llm-chat-resolve-model-backend ((backend (eql 'openai))
+ model)
+ (if (member model llm-chat-openai-models)
+ t))
+
+(defun llm-chat-openai-get-model ()
+ (if (member (llm-chat-get-model) llm-chat-openai-models)
+ (llm-chat-get-model)
+ "gpt-3.5-turbo"))
+
+(defun llm-chat-make-openai-backend ()
+ (make-llm-chat-backend
+ :api-endpoint "https://api.openai.com/v1/responses"
+ :api-key (auth-source-pick-first-password :host "api.openai.com")
+ :headers-fn #'llm-chat-openai-headers
+ :json-fn #'llm-chat-openai-json
+ :filter-fn #'llm-chat-openai-filter))
+
+(defun llm-chat-openai-json ()
+ (let ((json-object `((model . ,(llm-chat-openai-get-model))
+ (input . ,(llm-chat-get-history))
+ (temperature . ,(llm-chat-get-temperature))
+ (stream . ,(llm-chat-get-stream?)))))
+ (json-encode json-object)))
+
+(defun llm-chat-openai-headers (backend)
+ (list "-H" (concat "Authorization: " (concat "Bearer "
+ (llm-chat-backend-api-key backend)))))
+(defun llm-chat-openai-filter (proc string)
+ (llm-chat-data-filter proc string
+ #'llm-chat-openai-finished-p
+ #'llm-chat-openai-parse-content))
+
+(defun llm-chat-openai-finished-p (string)
+ (when-let* ((json-object (json-read-from-string string))
+ (type (alist-get 'type json-object)))
+ (string= type "response.output_item.done")))
+
+(defun llm-chat-openai-parse-content (string)
+ (when-let* ((json-object (json-read-from-string string))
+ (type (alist-get 'type json-object))
+ (text (alist-get 'delta json-object)))
+ (when (string-equal type "response.output_text.delta")
+ text)))
+
+(provide 'llm-chat-openai)
+
+;;; llm-chat-openai.el ends here