1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! OpenAI Chat Completions provider.
//!
//! Handles GPT models and any OpenAI-compatible endpoint (Groq,
//! Together, Ollama, DeepSeek, OpenRouter, vLLM, LMStudio, etc.).
//! The only difference between providers is the base URL and auth.
use async_trait::async_trait;
use futures::StreamExt;
use reqwest::header::{AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderValue};
use tokio::sync::mpsc;
use tracing::debug;
use super::message::{ContentBlock, Message, StopReason, Usage};
use super::provider::{Provider, ProviderError, ProviderRequest};
use super::stream::StreamEvent;
pub struct OpenAiProvider {
http: reqwest::Client,
base_url: String,
api_key: String,
}
impl OpenAiProvider {
pub fn new(base_url: &str, api_key: &str) -> Self {
let http = reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(300))
.build()
.expect("failed to build HTTP client");
Self {
http,
base_url: base_url.trim_end_matches('/').to_string(),
api_key: api_key.to_string(),
}
}
/// Build the request body in OpenAI format.
fn build_body(&self, request: &ProviderRequest) -> serde_json::Value {
// Convert our messages to OpenAI format.
// Key difference: system message goes in the messages array, not separate.
let mut messages = Vec::new();
// System message as first message.
if !request.system_prompt.is_empty() {
messages.push(serde_json::json!({
"role": "system",
"content": request.system_prompt,
}));
}
// Convert conversation messages.
for msg in &request.messages {
match msg {
Message::User(u) => {
let content = blocks_to_openai_content(&u.content);
messages.push(serde_json::json!({
"role": "user",
"content": content,
}));
}
Message::Assistant(a) => {
let mut msg_json = serde_json::json!({
"role": "assistant",
});
// Check for tool calls.
let tool_calls: Vec<serde_json::Value> = a
.content
.iter()
.filter_map(|b| match b {
ContentBlock::ToolUse { id, name, input } => Some(serde_json::json!({
"id": id,
"type": "function",
"function": {
"name": name,
"arguments": serde_json::to_string(input).unwrap_or_default(),
}
})),
_ => None,
})
.collect();
// Text content.
let text: String = a
.content
.iter()
.filter_map(|b| match b {
ContentBlock::Text { text } => Some(text.as_str()),
_ => None,
})
.collect::<Vec<_>>()
.join("");
if !text.is_empty() {
msg_json["content"] = serde_json::Value::String(text);
}
if !tool_calls.is_empty() {
msg_json["tool_calls"] = serde_json::Value::Array(tool_calls);
}
messages.push(msg_json);
}
Message::System(_) => {} // Already handled above.
}
}
// Handle tool results (OpenAI uses role: "tool").
// We need a second pass to convert our tool_result content blocks.
let mut final_messages = Vec::new();
for msg in messages {
if msg.get("role").and_then(|r| r.as_str()) == Some("user") {
// Check if this is actually a tool result message.
if let Some(content) = msg.get("content")
&& let Some(arr) = content.as_array()
{
let mut tool_results = Vec::new();
let mut other_content = Vec::new();
for block in arr {
if block.get("type").and_then(|t| t.as_str()) == Some("tool_result") {
tool_results.push(serde_json::json!({
"role": "tool",
"tool_call_id": block.get("tool_use_id").and_then(|v| v.as_str()).unwrap_or(""),
"content": block.get("content").and_then(|v| v.as_str()).unwrap_or(""),
}));
} else {
other_content.push(block.clone());
}
}
if !tool_results.is_empty() {
// Emit tool results as separate messages.
for tr in tool_results {
final_messages.push(tr);
}
if !other_content.is_empty() {
let mut m = msg.clone();
m["content"] = serde_json::Value::Array(other_content);
final_messages.push(m);
}
continue;
}
}
}
final_messages.push(msg);
}
// Build tools in OpenAI format.
let tools: Vec<serde_json::Value> = request
.tools
.iter()
.map(|t| {
serde_json::json!({
"type": "function",
"function": {
"name": t.name,
"description": t.description,
"parameters": t.input_schema,
}
})
})
.collect();
let mut body = serde_json::json!({
"model": request.model,
"messages": final_messages,
"max_tokens": request.max_tokens,
"stream": true,
});
if !tools.is_empty() {
body["tools"] = serde_json::Value::Array(tools);
}
if let Some(temp) = request.temperature {
body["temperature"] = serde_json::json!(temp);
}
body
}
}
#[async_trait]
impl Provider for OpenAiProvider {
fn name(&self) -> &str {
"openai"
}
async fn stream(
&self,
request: &ProviderRequest,
) -> Result<mpsc::Receiver<StreamEvent>, ProviderError> {
let url = format!("{}/chat/completions", self.base_url);
let body = self.build_body(request);
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {}", self.api_key))
.map_err(|e| ProviderError::Auth(e.to_string()))?,
);
debug!("OpenAI request to {url}");
let response = self
.http
.post(&url)
.headers(headers)
.json(&body)
.send()
.await
.map_err(|e| ProviderError::Network(e.to_string()))?;
let status = response.status();
if !status.is_success() {
let body_text = response.text().await.unwrap_or_default();
return match status.as_u16() {
401 | 403 => Err(ProviderError::Auth(body_text)),
429 => Err(ProviderError::RateLimited {
retry_after_ms: 1000,
}),
529 => Err(ProviderError::Overloaded),
413 => Err(ProviderError::RequestTooLarge(body_text)),
_ => Err(ProviderError::Network(format!("{status}: {body_text}"))),
};
}
// Parse OpenAI SSE stream.
let (tx, rx) = mpsc::channel(64);
tokio::spawn(async move {
let mut byte_stream = response.bytes_stream();
let mut buffer = String::new();
let mut current_tool_id = String::new();
let mut current_tool_name = String::new();
let mut current_tool_args = String::new();
let mut usage = Usage::default();
while let Some(chunk_result) = byte_stream.next().await {
let chunk = match chunk_result {
Ok(c) => c,
Err(e) => {
let _ = tx.send(StreamEvent::Error(e.to_string())).await;
break;
}
};
buffer.push_str(&String::from_utf8_lossy(&chunk));
while let Some(pos) = buffer.find("\n\n") {
let event_text = buffer[..pos].to_string();
buffer = buffer[pos + 2..].to_string();
for line in event_text.lines() {
let data = if let Some(d) = line.strip_prefix("data: ") {
d
} else {
continue;
};
if data == "[DONE]" {
let _ = tx
.send(StreamEvent::Done {
usage: usage.clone(),
stop_reason: Some(StopReason::EndTurn),
})
.await;
return;
}
let parsed: serde_json::Value = match serde_json::from_str(data) {
Ok(v) => v,
Err(_) => continue,
};
// Extract delta from choices[0].delta
let delta = match parsed
.get("choices")
.and_then(|c| c.get(0))
.and_then(|c| c.get("delta"))
{
Some(d) => d,
None => {
// Check for usage in the final chunk.
if let Some(u) = parsed.get("usage") {
usage.input_tokens = u
.get("prompt_tokens")
.and_then(|v| v.as_u64())
.unwrap_or(0);
usage.output_tokens = u
.get("completion_tokens")
.and_then(|v| v.as_u64())
.unwrap_or(0);
}
continue;
}
};
// Text content.
if let Some(content) = delta.get("content").and_then(|c| c.as_str())
&& !content.is_empty()
{
let _ = tx.send(StreamEvent::TextDelta(content.to_string())).await;
}
// Tool calls.
if let Some(tool_calls) = delta.get("tool_calls").and_then(|t| t.as_array())
{
for tc in tool_calls {
if let Some(func) = tc.get("function") {
if let Some(name) = func.get("name").and_then(|n| n.as_str()) {
// New tool call starting.
if !current_tool_id.is_empty()
&& !current_tool_args.is_empty()
{
// Emit the previous tool call.
let input: serde_json::Value =
serde_json::from_str(¤t_tool_args)
.unwrap_or_default();
let _ = tx
.send(StreamEvent::ContentBlockComplete(
ContentBlock::ToolUse {
id: current_tool_id.clone(),
name: current_tool_name.clone(),
input,
},
))
.await;
}
current_tool_id = tc
.get("id")
.and_then(|i| i.as_str())
.unwrap_or("")
.to_string();
current_tool_name = name.to_string();
current_tool_args.clear();
}
if let Some(args) =
func.get("arguments").and_then(|a| a.as_str())
{
current_tool_args.push_str(args);
}
}
}
}
}
}
}
// Emit any remaining tool call.
if !current_tool_id.is_empty() {
let input: serde_json::Value =
serde_json::from_str(¤t_tool_args).unwrap_or_default();
let _ = tx
.send(StreamEvent::ContentBlockComplete(ContentBlock::ToolUse {
id: current_tool_id,
name: current_tool_name,
input,
}))
.await;
}
let _ = tx
.send(StreamEvent::Done {
usage,
stop_reason: Some(StopReason::EndTurn),
})
.await;
});
Ok(rx)
}
}
/// Convert content blocks to OpenAI format.
fn blocks_to_openai_content(blocks: &[ContentBlock]) -> serde_json::Value {
if blocks.len() == 1
&& let ContentBlock::Text { text } = &blocks[0]
{
return serde_json::Value::String(text.clone());
}
let parts: Vec<serde_json::Value> = blocks
.iter()
.map(|b| match b {
ContentBlock::Text { text } => serde_json::json!({
"type": "text",
"text": text,
}),
ContentBlock::Image { media_type, data } => serde_json::json!({
"type": "image_url",
"image_url": {
"url": format!("data:{media_type};base64,{data}"),
}
}),
ContentBlock::ToolResult {
tool_use_id,
content,
is_error,
..
} => serde_json::json!({
"type": "tool_result",
"tool_use_id": tool_use_id,
"content": content,
"is_error": is_error,
}),
ContentBlock::Thinking { thinking, .. } => serde_json::json!({
"type": "text",
"text": thinking,
}),
ContentBlock::ToolUse { name, input, .. } => serde_json::json!({
"type": "text",
"text": format!("[Tool call: {name}({input})]"),
}),
})
.collect();
serde_json::Value::Array(parts)
}