interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / spark-adapters / src / providers / anthropic.rs

208 lines · 6393 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
17use reqwest::Client;
18use serde_json::{json, Value};
19
20use crate::models::{ChatMessage, NormalizedChunk};
21
22pub fn build_anthropic_headers(api_key: &str) -> HeaderMap {
23 let mut headers = HeaderMap::new();
24 headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
25 headers.insert(
26 reqwest::header::HeaderName::from_static("x-api-key"),
27 HeaderValue::from_str(api_key.trim()).unwrap_or_else(|_| HeaderValue::from_static("")),
28 );
29 headers.insert(
30 reqwest::header::HeaderName::from_static("anthropic-version"),
31 HeaderValue::from_static("2023-06-01"),
32 );
33 headers
34}
35
36pub fn format_anthropic_payload(
37 model: &str,
38 messages: &[ChatMessage],
39 temperature: Option<f32>,
40 stream: bool,
41) -> Value {
42 let mut system_prompt = String::new();
43 let mut formatted_msgs = Vec::new();
44
45 for m in messages {
46 if m.role == "system" {
47 if !system_prompt.is_empty() {
48 system_prompt.push_str(
49 "
50
51",
52 );
53 }
54 system_prompt.push_str(&m.content);
55 } else {
56 formatted_msgs.push(json!({
57 "role": if m.role == "assistant" { "assistant" } else { "user" },
58 "content": m.content
59 }));
60 }
61 }
62
63 if formatted_msgs.is_empty() {
64 formatted_msgs.push(json!({
65 "role": "user",
66 "content": "Hello"
67 }));
68 }
69
70 let temp_f64: f64 = temperature
71 .map(|t| (t as f64 * 1000.0).round() / 1000.0)
72 .unwrap_or(0.7);
73
74 let mut payload = json!({
75 "model": model,
76 "messages": formatted_msgs,
77 "max_tokens": 4096,
78 "stream": stream,
79 "temperature": temp_f64
80 });
81
82 if !system_prompt.is_empty() {
83 payload["system"] = json!(system_prompt);
84 }
85
86 payload
87}
88
89pub fn parse_anthropic_sse_line(line: &str) -> Option<NormalizedChunk> {
90 let trimmed = line.trim();
91 if !trimmed.starts_with("data:") {
92 return None;
93 }
94
95 let payload = trimmed.strip_prefix("data:")?.trim();
96 let val: Value = serde_json::from_str(payload).ok()?;
97 let event_type = val.get("type").and_then(Value::as_str).unwrap_or("");
98
99 match event_type {
100 "content_block_delta" => {
101 let delta = val.get("delta")?;
102 let delta_type = delta.get("type").and_then(Value::as_str).unwrap_or("");
103 if delta_type == "text_delta" {
104 let text = delta
105 .get("text")
106 .and_then(Value::as_str)
107 .unwrap_or("")
108 .to_string();
109 Some(NormalizedChunk {
110 content: text,
111 reasoning: String::new(),
112 is_done: false,
113 })
114 } else if delta_type == "thinking_delta" {
115 let thinking = delta
116 .get("thinking")
117 .and_then(Value::as_str)
118 .unwrap_or("")
119 .to_string();
120 Some(NormalizedChunk {
121 content: String::new(),
122 reasoning: thinking,
123 is_done: false,
124 })
125 } else {
126 None
127 }
128 }
129 "message_stop" => Some(NormalizedChunk {
130 content: String::new(),
131 reasoning: String::new(),
132 is_done: true,
133 }),
134 _ => None,
135 }
136}
137
138pub async fn call_anthropic_unary(
139 client: &Client,
140 endpoint: &str,
141 model: &str,
142 api_key: &str,
143 messages: &[ChatMessage],
144 temperature: Option<f32>,
145) -> Result<(String, Option<String>, usize), String> {
146 let payload = format_anthropic_payload(model, messages, temperature, false);
147 let headers = build_anthropic_headers(api_key);
148
149 let res = client
150 .post(endpoint)
151 .headers(headers)
152 .json(&payload)
153 .send()
154 .await
155 .map_err(|e| format!("Failed to send request to Anthropic: {}", e))?;
156
157 if !res.status().is_success() {
158 let status = res.status();
159 let body = res.text().await.unwrap_or_default();
160 return Err(format!("Anthropic returned HTTP {}: {}", status, body));
161 }
162
163 let val: Value = res
164 .json()
165 .await
166 .map_err(|e| format!("Failed to parse Anthropic JSON response: {}", e))?;
167
168 let content_blocks = val
169 .get("content")
170 .and_then(|c| c.as_array())
171 .ok_or_else(|| "Malformed Anthropic response: missing content array".to_string())?;
172
173 let mut text_acc = String::new();
174 let mut reasoning_acc = String::new();
175
176 for block in content_blocks {
177 let block_type = block.get("type").and_then(Value::as_str).unwrap_or("");
178 if block_type == "text" {
179 if let Some(t) = block.get("text").and_then(Value::as_str) {
180 text_acc.push_str(t);
181 }
182 } else if block_type == "thinking" {
183 if let Some(th) = block.get("thinking").and_then(Value::as_str) {
184 reasoning_acc.push_str(th);
185 }
186 }
187 }
188
189 let input_tokens = val
190 .get("usage")
191 .and_then(|u| u.get("input_tokens"))
192 .and_then(|t| t.as_u64())
193 .unwrap_or(0);
194 let output_tokens = val
195 .get("usage")
196 .and_then(|u| u.get("output_tokens"))
197 .and_then(|t| t.as_u64())
198 .unwrap_or(0);
199 let total_tokens = (input_tokens + output_tokens) as usize;
200
201 let reasoning = if reasoning_acc.is_empty() {
202 None
203 } else {
204 Some(reasoning_acc)
205 };
206
207 Ok((text_acc, reasoning, total_tokens))
208}