latexsnipper-runtime 3.1.0

Runtime abstraction — Session, Provider, ModelHandle
Documentation
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
419
420
421
422
423
424
425
426
427
428
//! Remote API Provider — optional HTTP-based model execution.
//!
//! Enabled via the `remote-api` Cargo feature. Provides an OpenAI-compatible
//! API client for vision-language and prompt-based model calls.
//!
//! All remote outputs are validated against the configured JSON schema before
//! being returned; schema violations produce diagnostics instead of panicking.

use latexsnipper_ast::{Diagnostic, DiagnosticLevel, ProviderCallReport, ProviderReport};
use std::time::Instant;

use crate::api_provider::{ApiProviderConfig, PromptProfile, UploadScope};

/// Raw API response with content and token usage extracted from the full response body.
struct ApiRawResponse {
    content: String,
    input_tokens: Option<u32>,
    output_tokens: Option<u32>,
}

/// Result of a single remote API call.
#[derive(Debug, Clone)]
pub struct RemoteApiResult {
    /// Raw text response from the API.
    pub text: String,
    /// Parsed JSON (if the response was JSON).
    pub parsed_json: Option<serde_json::Value>,
    /// Whether the response passed schema validation.
    pub schema_valid: bool,
    /// Elapsed time in milliseconds.
    pub elapsed_ms: u64,
    /// Token usage if reported by the API.
    pub input_tokens: Option<u32>,
    pub output_tokens: Option<u32>,
}

impl RemoteApiResult {
    /// Check if the response is usable (non-empty, schema-valid if schema required).
    pub fn is_usable(&self) -> bool {
        !self.text.is_empty() && self.schema_valid
    }

    /// Check if the response is usable for a specific profile.
    /// Allows responses without schema validation when the profile doesn't require one.
    pub fn is_usable_for_profile(&self, profile: &PromptProfile) -> bool {
        !self.text.is_empty() && (profile.output_schema.is_none() || self.schema_valid)
    }
}

/// A remote API provider that executes prompts via HTTP.
///
/// Supports OpenAI-compatible chat completion endpoints with image support.
/// Use `RemoteApiProvider::new(config)` to create, then call `execute()`.
pub struct RemoteApiProvider {
    pub config: ApiProviderConfig,
}

impl RemoteApiProvider {
    pub fn new(config: ApiProviderConfig) -> Self {
        Self { config }
    }

    /// Execute a prompt with an optional base64-encoded image.
    ///
    /// Returns the API response along with diagnostics and timing information.
    pub async fn execute(
        &self,
        profile: &PromptProfile,
        image_base64: Option<&str>,
    ) -> (RemoteApiResult, Vec<Diagnostic>, ProviderReport) {
        let start = Instant::now();
        let mut diagnostics = Vec::new();
        let report_id = format!("remote_{}", self.config.provider);

        // 1. Check upload policy
        if let Some(_img) = image_base64 {
            if !self.may_upload(UploadScope::PageImage) {
                diagnostics.push(
                    Diagnostic::new(
                        DiagnosticLevel::Error,
                        "E_UPLOAD_BLOCKED",
                        "Upload policy prevented image transmission",
                    )
                    .with_recoverable(true),
                );
                let elapsed = start.elapsed().as_millis() as u64;
                return (
                    RemoteApiResult {
                        text: String::new(),
                        parsed_json: None,
                        schema_valid: false,
                        elapsed_ms: elapsed,
                        input_tokens: None,
                        output_tokens: None,
                    },
                    diagnostics,
                    ProviderReport {
                        provider_id: report_id,
                        provider_kind: "RemoteApi".to_string(),
                        model: Some(self.config.model.clone()),
                        tasks: vec![format!("{:?}", profile.task)],
                        calls: vec![ProviderCallReport {
                            call_id: "call_1".to_string(),
                            model: Some(self.config.model.clone()),
                            input_tokens: None,
                            output_tokens: None,
                            elapsed_ms: elapsed,
                            success: false,
                            error: Some(
                                "E_UPLOAD_BLOCKED: Upload policy prevented image transmission"
                                    .to_string(),
                            ),
                        }],
                        fallback_used: false,
                        total_elapsed_ms: elapsed,
                    },
                );
            }
        }

        // 2. Build the request payload
        let payload = match self.build_payload(profile, image_base64) {
            Ok(p) => p,
            Err(e) => {
                diagnostics.push(Diagnostic::new(DiagnosticLevel::Error, "E_PAYLOAD", &e));
                let elapsed = start.elapsed().as_millis() as u64;
                return (
                    RemoteApiResult {
                        text: String::new(),
                        parsed_json: None,
                        schema_valid: false,
                        elapsed_ms: elapsed,
                        input_tokens: None,
                        output_tokens: None,
                    },
                    diagnostics,
                    ProviderReport {
                        provider_id: report_id,
                        provider_kind: "RemoteApi".to_string(),
                        model: Some(self.config.model.clone()),
                        tasks: vec![format!("{:?}", profile.task)],
                        calls: vec![ProviderCallReport {
                            call_id: "call_1".to_string(),
                            model: Some(self.config.model.clone()),
                            input_tokens: None,
                            output_tokens: None,
                            elapsed_ms: elapsed,
                            success: false,
                            error: Some(format!("E_PAYLOAD: {}", e)),
                        }],
                        fallback_used: false,
                        total_elapsed_ms: elapsed,
                    },
                );
            }
        };

        // 3. Send HTTP request
        let response = self.send_request(&payload).await;
        let elapsed_ms = start.elapsed().as_millis() as u64;

        let (text, parsed_json, input_tokens, output_tokens) = match response {
            Ok(raw) => {
                let parsed = serde_json::from_str::<serde_json::Value>(&raw.content).ok();
                (raw.content, parsed, raw.input_tokens, raw.output_tokens)
            }
            Err(e) => {
                diagnostics.push(Diagnostic::new(DiagnosticLevel::Error, "E_API_CALL", &e));
                let report = ProviderReport {
                    provider_id: report_id,
                    provider_kind: "RemoteApi".to_string(),
                    model: Some(self.config.model.clone()),
                    tasks: vec![format!("{:?}", profile.task)],
                    calls: vec![ProviderCallReport {
                        call_id: "call_1".to_string(),
                        model: Some(self.config.model.clone()),
                        input_tokens: None,
                        output_tokens: None,
                        elapsed_ms,
                        success: false,
                        error: Some(e),
                    }],
                    fallback_used: false,
                    total_elapsed_ms: elapsed_ms,
                };
                return (
                    RemoteApiResult {
                        text: String::new(),
                        parsed_json: None,
                        schema_valid: false,
                        elapsed_ms,
                        input_tokens: None,
                        output_tokens: None,
                    },
                    diagnostics,
                    report,
                );
            }
        };

        // 4. Schema validation
        let schema_valid =
            if let (Some(schema), Some(json)) = (&profile.output_schema, &parsed_json) {
                validate_json_against_schema(json, schema)
            } else {
                true
            };

        if !schema_valid {
            diagnostics.push(
                Diagnostic::new(
                    DiagnosticLevel::Warning,
                    "E_SCHEMA_OUTPUT",
                    "API response did not match the expected output schema",
                )
                .with_recoverable(true),
            );
        }

        // 5. Build report
        let report = ProviderReport {
            provider_id: report_id,
            provider_kind: "RemoteApi".to_string(),
            model: Some(self.config.model.clone()),
            tasks: vec![format!("{:?}", profile.task)],
            calls: vec![ProviderCallReport {
                call_id: "call_1".to_string(),
                model: Some(self.config.model.clone()),
                input_tokens,
                output_tokens,
                elapsed_ms,
                success: true,
                error: None,
            }],
            fallback_used: false,
            total_elapsed_ms: elapsed_ms,
        };

        (
            RemoteApiResult {
                text,
                parsed_json,
                schema_valid,
                elapsed_ms,
                input_tokens,
                output_tokens,
            },
            diagnostics,
            report,
        )
    }

    /// Check whether the upload policy allows sending the given scope of data.
    fn may_upload(&self, scope: UploadScope) -> bool {
        self.config.upload_policy.allows(scope)
    }

    /// Build the JSON request payload for an OpenAI-compatible chat endpoint.
    fn build_payload(
        &self,
        profile: &PromptProfile,
        image_base64: Option<&str>,
    ) -> Result<serde_json::Value, String> {
        let mut messages = Vec::new();

        if let Some(system) = &profile.system {
            messages.push(serde_json::json!({
                "role": "system",
                "content": system
            }));
        }

        let mut content = Vec::new();
        content.push(serde_json::json!({
            "type": "text",
            "text": &profile.instruction
        }));

        if let Some(b64) = image_base64 {
            content.push(serde_json::json!({
                "type": "image_url",
                "image_url": {
                    "url": format!("data:image/png;base64,{}", b64)
                }
            }));
        }

        messages.push(serde_json::json!({
            "role": "user",
            "content": content
        }));

        let mut body = serde_json::json!({
            "model": self.config.model,
            "messages": messages,
            "max_tokens": profile.max_tokens.unwrap_or(1024),
        });

        if let Some(temp) = profile.temperature {
            body["temperature"] = serde_json::json!(temp);
        }

        if profile.output_schema.is_some() {
            body["response_format"] = serde_json::json!({
                "type": "json_object"
            });
        }

        Ok(body)
    }

    /// Send the request and return a structured response with token usage.
    async fn send_request(&self, payload: &serde_json::Value) -> Result<ApiRawResponse, String> {
        let endpoint = self
            .config
            .endpoint
            .as_deref()
            .unwrap_or("https://api.openai.com/v1/chat/completions");

        let api_key = self
            .config
            .api_key_env
            .as_ref()
            .and_then(|env_var| std::env::var(env_var).ok());

        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_millis(self.config.timeout_ms))
            .build()
            .map_err(|e| format!("E_API_HTTP: Failed to create HTTP client: {}", e))?;

        let mut req = client.post(endpoint).json(payload);

        if let Some(key) = &api_key {
            req = req.header("Authorization", format!("Bearer {}", key));
        }

        let resp = req.send().await.map_err(|e| {
            if e.is_timeout() {
                format!(
                    "E_API_TIMEOUT: Request timed out after {}ms",
                    self.config.timeout_ms
                )
            } else if e.is_connect() {
                format!("E_API_HTTP: Connection failed: {}", e)
            } else {
                format!("E_API_HTTP: Request failed: {}", e)
            }
        })?;
        let status = resp.status();
        let body = resp
            .text()
            .await
            .map_err(|e| format!("E_API_HTTP: Failed to read response body: {}", e))?;

        if status.as_u16() == 401 {
            return Err("E_API_AUTH: Authentication failed (status 401)".to_string());
        }
        if status.as_u16() == 429 {
            return Err("E_API_RATE_LIMIT: Rate limited (status 429)".to_string());
        }
        if !status.is_success() {
            return Err(format!(
                "E_API_HTTP: API error {}: {}",
                status.as_u16(),
                body
            ));
        }

        let content = extract_content_from_openai_response(&body);
        let (input_tokens, output_tokens) = extract_token_usage(&body);
        Ok(ApiRawResponse {
            content,
            input_tokens,
            output_tokens,
        })
    }
}

/// Extract the text content from an OpenAI-compatible chat completion response.
fn extract_content_from_openai_response(body: &str) -> String {
    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body) {
        if let Some(choice) = parsed["choices"].get(0) {
            if let Some(content) = choice["message"]["content"].as_str() {
                return content.to_string();
            }
        }
    }
    body.to_string()
}

/// Extract token usage from an OpenAI-compatible response JSON.
fn extract_token_usage(body: &str) -> (Option<u32>, Option<u32>) {
    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body) {
        let usage = &parsed["usage"];
        let input = usage["prompt_tokens"].as_u64().map(|v| v as u32);
        let output = usage["completion_tokens"].as_u64().map(|v| v as u32);
        (input, output)
    } else {
        (None, None)
    }
}

/// Simple JSON schema validation.
///
/// Checks that the response JSON has all top-level keys that the schema specifies
/// as `required` or `properties`. This is a lightweight check; a full schema
/// validator would require a JSON Schema library.
fn validate_json_against_schema(json: &serde_json::Value, schema: &serde_json::Value) -> bool {
    if let Some(required) = schema.get("required").and_then(|v| v.as_array()) {
        for key in required {
            if let Some(key_str) = key.as_str() {
                if json.get(key_str).is_none() {
                    return false;
                }
            }
        }
    }

    if let Some(properties) = schema.get("properties").and_then(|v| v.as_object()) {
        for (key, prop_schema) in properties {
            if json.get(key).is_none() && prop_schema.get("default").is_none() {
                return false;
            }
        }
    }

    true
}