interplane.Get Omega
Read in your language

spark-adapters

Hardware abstraction adapters for local AI accelerators

Brought by drakestapleton

branch main Branches Tags History

spark-adapters / src / providers / openai.rs

143 lines · 4110 bytes Raw Blame History
1use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
2use reqwest::Client;
3use serde_json::{json, Value};
4
5use crate::models::{ChatMessage, NormalizedChunk};
6
7pub fn build_headers(api_key: Option<&str>, custom_headers: Option<Vec<(String, String)>>) -> HeaderMap {
8 let mut headers = HeaderMap::new();
9 headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
10
11 if let Some(key) = api_key {
12 let auth_val = format!("Bearer {}", key.trim());
13 if let Ok(hv) = HeaderValue::from_str(&auth_val) {
14 headers.insert(AUTHORIZATION, hv);
15 }
16 }
17
18 if let Some(custom) = custom_headers {
19 for (k, v) in custom {
20 if let (Ok(hk), Ok(hv)) = (
21 reqwest::header::HeaderName::from_bytes(k.as_bytes()),
22 HeaderValue::from_str(&v)
23 ) {
24 headers.insert(hk, hv);
25 }
26 }
27 }
28
29 headers
30}
31
32pub fn format_openai_payload(model: &str, messages: &[ChatMessage], temperature: Option<f32>, stream: bool) -> Value {
33 let formatted_msgs: Vec<Value> = messages
34 .iter()
35 .map(|m| {
36 json!({
37 "role": m.role,
38 "content": m.content
39 })
40 })
41 .collect();
42
43 json!({
44 "model": model,
45 "messages": formatted_msgs,
46 "temperature": temperature.unwrap_or(0.7),
47 "stream": stream
48 })
49}
50
51pub fn parse_openai_sse_line(line: &str) -> Option<NormalizedChunk> {
52 let trimmed = line.trim();
53 if !trimmed.starts_with("data:") {
54 return None;
55 }
56
57 let payload = trimmed.strip_prefix("data:")?.trim();
58 if payload == "[DONE]" {
59 return Some(NormalizedChunk {
60 content: String::new(),
61 reasoning: String::new(),
62 is_done: true,
63 });
64 }
65
66 let val: Value = serde_json::from_str(payload).ok()?;
67 let choice = val.get("choices")?.as_array()?.first()?;
68 let delta = choice.get("delta")?;
69
70 let content = delta.get("content").and_then(Value::as_str).unwrap_or("").to_string();
71 let reasoning = delta.get("reasoning_content")
72 .or_else(|| delta.get("reasoning"))
73 .and_then(Value::as_str)
74 .unwrap_or("")
75 .to_string();
76
77 Some(NormalizedChunk {
78 content,
79 reasoning,
80 is_done: false,
81 })
82}
83
84pub async fn call_openai_unary(
85 client: &Client,
86 endpoint: &str,
87 model: &str,
88 api_key: Option<&str>,
89 messages: &[ChatMessage],
90 temperature: Option<f32>,
91) -> Result<(String, Option<String>, usize), String> {
92 let payload = format_openai_payload(model, messages, temperature, false);
93 let headers = build_headers(api_key, None);
94
95 let res = client
96 .post(endpoint)
97 .headers(headers)
98 .json(&payload)
99 .send()
100 .await
101 .map_err(|e| format!("Failed to send request to {}: {}", endpoint, e))?;
102
103 if !res.status().is_success() {
104 let status = res.status();
105 let body = res.text().await.unwrap_or_default();
106 return Err(format!("Provider returned HTTP {}: {}", status, body));
107 }
108
109 let val: Value = res
110 .json()
111 .await
112 .map_err(|e| format!("Failed to parse JSON response: {}", e))?;
113
114 let choice = val
115 .get("choices")
116 .and_then(|c| c.as_array())
117 .and_then(|a| a.first())
118 .ok_or_else(|| "Malformed response: missing choices array".to_string())?;
119
120 let message = choice
121 .get("message")
122 .ok_or_else(|| "Missing message object in choice".to_string())?;
123
124 let content = message
125 .get("content")
126 .and_then(|v| v.as_str())
127 .unwrap_or("")
128 .to_string();
129
130 let reasoning = message
131 .get("reasoning_content")
132 .or_else(|| message.get("reasoning"))
133 .and_then(|v| v.as_str())
134 .map(|s| s.to_string());
135
136 let token_count = val
137 .get("usage")
138 .and_then(|u| u.get("total_tokens"))
139 .and_then(|t| t.as_u64())
140 .unwrap_or(0) as usize;
141
142 Ok((content, reasoning, token_count))
143}