|
17 | 17 |
|
18 | 18 | (def ^:private messages-path "/v1/messages") |
19 | 19 |
|
| 20 | +(defn ^:private any-assistant-message-without-thinking-previously? |
| 21 | + "If there is a assistant message, which has no previous any role message with thinking content, returns true." |
| 22 | + [messages] |
| 23 | + (loop [msgs messages |
| 24 | + seen-thinking? false] |
| 25 | + (if-let [msg (first msgs)] |
| 26 | + (let [is-assistant? (= "assistant" (:role msg)) |
| 27 | + has-thinking? (and (vector? (:content msg)) |
| 28 | + (some #(= "thinking" (:type %)) (:content msg)))] |
| 29 | + (cond |
| 30 | + ;; If this is an assistant message and we haven't seen thinking before, return true |
| 31 | + (and is-assistant? (not seen-thinking?) (not has-thinking?)) |
| 32 | + true |
| 33 | + |
| 34 | + ;; If this message has thinking content, mark it as seen |
| 35 | + has-thinking? |
| 36 | + (recur (rest msgs) true) |
| 37 | + |
| 38 | + ;; Otherwise continue |
| 39 | + :else |
| 40 | + (recur (rest msgs) seen-thinking?))) |
| 41 | + ;; No assistant message found without previous thinking |
| 42 | + false))) |
| 43 | + |
| 44 | +(defn ^:private fix-non-thinking-assistant-messages [messages] |
| 45 | + (if (any-assistant-message-without-thinking-previously? messages) |
| 46 | + ;; Anthropic doesn't like assistant messages without thinking blocks, |
| 47 | + ;; we force to be a user one when this happens |
| 48 | + ;; (MCP prompts that return assistant messages as initial step like clojureMCP) |
| 49 | + ;; https://clojurians.slack.com/archives/C093426FPUG/p1757622242502969 |
| 50 | + (mapv (fn [{:keys [role content] :as msg}] |
| 51 | + (if (= "assistant" role) |
| 52 | + {:role "user" |
| 53 | + :content content} |
| 54 | + msg)) |
| 55 | + messages) |
| 56 | + messages)) |
| 57 | + |
20 | 58 | (defn ^:private ->tools [tools web-search] |
21 | 59 | (cond-> |
22 | 60 | (mapv (fn [tool] |
|
105 | 143 | tools web-search extra-payload]} |
106 | 144 | {:keys [on-message-received on-error on-reason on-prepare-tool-call on-tools-called on-usage-updated]}] |
107 | 145 | (let [messages (concat (normalize-messages past-messages) |
108 | | - (normalize-messages user-messages)) |
| 146 | + (normalize-messages (fix-non-thinking-assistant-messages user-messages))) |
109 | 147 | body (merge (assoc-some |
110 | 148 | {:model model |
111 | 149 | :messages (add-cache-to-last-message messages) |
|
0 commit comments