|
| 1 | +(ns eca.llm-providers.anthropic |
| 2 | + (:require |
| 3 | + [cheshire.core :as json] |
| 4 | + [clojure.java.io :as io] |
| 5 | + [clojure.string :as str] |
| 6 | + [eca.logger :as logger] |
| 7 | + [hato.client :as http])) |
| 8 | + |
| 9 | +(def ^:private logger-tag "[ANTHROPIC]") |
| 10 | + |
| 11 | +(def ^:private url "https://api.anthropic.com/v1/messages") |
| 12 | + |
| 13 | +(defn ^:private raw-data->messages [data] |
| 14 | + (let [{:keys [type delta]} (json/parse-string data true)] |
| 15 | + (case type |
| 16 | + "content_block_delta" (case (:type delta) |
| 17 | + "text_delta" {:message (:text delta)} |
| 18 | + (logger/warn "Unkown response delta type" (:type delta))) |
| 19 | + "message_stop" {:finish-reason type} |
| 20 | + nil))) |
| 21 | + |
| 22 | +(defn ^:private context->system [{:keys [role behavior context]}] |
| 23 | + (format "%s\n%s\n%s\n" |
| 24 | + role behavior context)) |
| 25 | + |
| 26 | +(defn completion! [{:keys [model user-prompt temperature context max-tokens api-key] |
| 27 | + :or {max-tokens 1024 |
| 28 | + temperature 1.0}} |
| 29 | + {:keys [on-message-received on-error]}] |
| 30 | + (let [body {:model model |
| 31 | + :messages [{:role "user" :content user-prompt}] |
| 32 | + :max_tokens max-tokens |
| 33 | + :temperature temperature |
| 34 | + ;; TODO support :thinking |
| 35 | + :stream true |
| 36 | + :system (context->system context)} |
| 37 | + api-key (or api-key |
| 38 | + (System/getenv "ANTHROPIC_API_KEY"))] |
| 39 | + (http/post |
| 40 | + url |
| 41 | + {:headers {"x-api-key" api-key |
| 42 | + "anthropic-version" "2023-06-01" |
| 43 | + "Content-Type" "application/json"} |
| 44 | + :body (json/generate-string body) |
| 45 | + :throw-exceptions? false |
| 46 | + :async? true |
| 47 | + :as :stream} |
| 48 | + (fn [{:keys [status body]}] |
| 49 | + (try |
| 50 | + (with-open [rdr (io/reader body)] |
| 51 | + (doseq [line (line-seq rdr)] |
| 52 | + (if (not= 200 status) |
| 53 | + (let [msg line] |
| 54 | + (logger/warn logger-tag "Unexpected response status" status "." msg) |
| 55 | + (on-error {:message (str "Anthropic response status: " status)})) |
| 56 | + (when (str/starts-with? line "data: ") |
| 57 | + (let [data (subs line 6)] |
| 58 | + (when-let [message (raw-data->messages data)] |
| 59 | + (on-message-received message))))))) |
| 60 | + (catch Exception e |
| 61 | + (on-error {:exception e})))) |
| 62 | + (fn [e] |
| 63 | + (on-error {:exception e}))))) |
0 commit comments