Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/spark-adapters/blob/main/src/providers/anthropic.rs # spark-adapters Hardware abstraction adapters for local AI accelerators Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `spark-adapters / src / providers / anthropic.rs` 162 lines ยท 5320 bytes Raw Blame History 1 use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE}; 2 use reqwest::Client; 3 use serde_json::{json, Value}; 4 5 use crate::models::{ChatMessage, NormalizedChunk}; 6 7 pub fn build_anthropic_headers(api_key: &str) -> HeaderMap { 8 let mut headers = HeaderMap::new(); 9 headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); 10 headers.insert( 11 reqwest::header::HeaderName::from_static("x-api-key"), 12 HeaderValue::from_str(api_key.trim()).unwrap_or_else(|_| HeaderValue::from_static("")) 13 ); 14 headers.insert( 15 reqwest::header::HeaderName::from_static("anthropic-version"), 16 HeaderValue::from_static("2023-06-01") 17 ); 18 headers 19 } 20 21 pub fn format_anthropic_payload(model: &str, messages: &[ChatMessage], temperature: Option, stream: bool) -> Value { 22 let mut system_prompt = String::new(); 23 let mut formatted_msgs = Vec::new(); 24 25 for m in messages { 26 if m.role == "system" { 27 if !system_prompt.is_empty() { 28 system_prompt.push_str(" 29 30 "); 31 } 32 system_prompt.push_str(&m.content); 33 } else { 34 formatted_msgs.push(json!({ 35 "role": if m.role == "assistant" { "assistant" } else { "user" }, 36 "content": m.content 37 })); 38 } 39 } 40 41 if formatted_msgs.is_empty() { 42 formatted_msgs.push(json!({ 43 "role": "user", 44 "content": "Hello" 45 })); 46 } 47 48 let mut payload = json!({ 49 "model": model, 50 "messages": formatted_msgs, 51 "max_tokens": 4096, 52 "stream": stream, 53 "temperature": temperature.unwrap_or(0.7) 54 }); 55 56 if !system_prompt.is_empty() { 57 payload["system"] = json!(system_prompt); 58 } 59 60 payload 61 } 62 63 pub fn parse_anthropic_sse_line(line: &str) -> Option { 64 let trimmed = line.trim(); 65 if !trimmed.starts_with("data:") { 66 return None; 67 } 68 69 let payload = trimmed.strip_prefix("data:")?.trim(); 70 let val: Value = serde_json::from_str(payload).ok()?; 71 let event_type = val.get("type").and_then(Value::as_str).unwrap_or(""); 72 73 match event_type { 74 "content_block_delta" => { 75 let delta = val.get("delta")?; 76 let delta_type = delta.get("type").and_then(Value::as_str).unwrap_or(""); 77 if delta_type == "text_delta" { 78 let text = delta.get("text").and_then(Value::as_str).unwrap_or("").to_string(); 79 Some(NormalizedChunk { 80 content: text, 81 reasoning: String::new(), 82 is_done: false, 83 }) 84 } else if delta_type == "thinking_delta" { 85 let thinking = delta.get("thinking").and_then(Value::as_str).unwrap_or("").to_string(); 86 Some(NormalizedChunk { 87 content: String::new(), 88 reasoning: thinking, 89 is_done: false, 90 }) 91 } else { 92 None 93 } 94 } 95 "message_stop" => Some(NormalizedChunk { 96 content: String::new(), 97 reasoning: String::new(), 98 is_done: true, 99 }), 100 _ => None, 101 } 102 } 103 104 pub async fn call_anthropic_unary( 105 client: &Client, 106 endpoint: &str, 107 model: &str, 108 api_key: &str, 109 messages: &[ChatMessage], 110 temperature: Option, 111 ) -> Result<(String, Option, usize), String> { 112 let payload = format_anthropic_payload(model, messages, temperature, false); 113 let headers = build_anthropic_headers(api_key); 114 115 let res = client 116 .post(endpoint) 117 .headers(headers) 118 .json(&payload) 119 .send() 120 .await 121 .map_err(|e| format!("Failed to send request to Anthropic: {}", e))?; 122 123 if !res.status().is_success() { 124 let status = res.status(); 125 let body = res.text().await.unwrap_or_default(); 126 return Err(format!("Anthropic returned HTTP {}: {}", status, body)); 127 } 128 129 let val: Value = res 130 .json() 131 .await 132 .map_err(|e| format!("Failed to parse Anthropic JSON response: {}", e))?; 133 134 let content_blocks = val 135 .get("content") 136 .and_then(|c| c.as_array()) 137 .ok_or_else(|| "Malformed Anthropic response: missing content array".to_string())?; 138 139 let mut text_acc = String::new(); 140 let mut reasoning_acc = String::new(); 141 142 for block in content_blocks { 143 let block_type = block.get("type").and_then(Value::as_str).unwrap_or(""); 144 if block_type == "text" { 145 if let Some(t) = block.get("text").and_then(Value::as_str) { 146 text_acc.push_str(t); 147 } 148 } else if block_type == "thinking" { 149 if let Some(th) = block.get("thinking").and_then(Value::as_str) { 150 reasoning_acc.push_str(th); 151 } 152 } 153 } 154 155 let input_tokens = val.get("usage").and_then(|u| u.get("input_tokens")).and_then(|t| t.as_u64()).unwrap_or(0); 156 let output_tokens = val.get("usage").and_then(|u| u.get("output_tokens")).and_then(|t| t.as_u64()).unwrap_or(0); 157 let total_tokens = (input_tokens + output_tokens) as usize; 158 159 let reasoning = if reasoning_acc.is_empty() { None } else { Some(reasoning_acc) }; 160 161 Ok((text_acc, reasoning, total_tokens)) 162 }