-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpython.rs
More file actions
502 lines (447 loc) · 17.8 KB
/
Copy pathpython.rs
File metadata and controls
502 lines (447 loc) · 17.8 KB
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
use pyo3::prelude::*;
use serde::{Deserialize, Serialize};
// Import our types and conversion traits
use crate::providers::anthropic::convert::{
anthropic_input_messages_to_universal_messages, universal_messages_to_anthropic_input_messages,
};
use crate::providers::anthropic::generated as anthropic;
use crate::providers::google::generated as google;
use crate::providers::openai::convert::{
messages_to_chat_completion_messages, ChatCompletionRequestMessageExt,
};
use crate::providers::openai::generated as openai;
use crate::serde_json;
use crate::universal::{convert::TryFromLLM, Message};
/// Convert Python object to Rust type via JSON
fn py_to_rust<'py, T>(py: Python<'py>, value: &Bound<'py, PyAny>) -> PyResult<T>
where
T: for<'de> Deserialize<'de>,
{
// Convert Python object to JSON string
let json_str = pyo3::types::PyModule::import(py, "json")?
.getattr("dumps")?
.call1((value,))?
.extract::<String>()?;
// Deserialize from JSON
serde_json::from_str(&json_str).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Failed to parse input: {}", e))
})
}
/// Convert Rust type to Python object via JSON
fn rust_to_py<'py, T>(py: Python<'py>, value: &T) -> PyResult<Bound<'py, PyAny>>
where
T: Serialize,
{
// Serialize to JSON string
let json_str = serde_json::to_string(value).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Failed to serialize: {}", e))
})?;
// Convert JSON string to Python object
pyo3::types::PyModule::import(py, "json")?
.getattr("loads")?
.call1((json_str,))
}
/// Generic conversion from provider to Lingua
fn convert_to_lingua<'py, T, U>(
py: Python<'py>,
value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>>
where
T: for<'de> Deserialize<'de>,
U: TryFromLLM<T> + Serialize,
<U as TryFromLLM<T>>::Error: std::fmt::Debug,
{
let provider_msg: T = py_to_rust(py, value)?;
let lingua_msg = U::try_from(provider_msg).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Conversion error: {:?}", e))
})?;
rust_to_py(py, &lingua_msg)
}
/// Generic conversion from Lingua to provider
fn convert_from_lingua<'py, T, U>(
py: Python<'py>,
value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>>
where
T: for<'de> Deserialize<'de>,
U: TryFromLLM<T> + Serialize,
<U as TryFromLLM<T>>::Error: std::fmt::Debug,
{
let lingua_msg: T = py_to_rust(py, value)?;
let provider_msg = U::try_from(lingua_msg).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Conversion error: {:?}", e))
})?;
rust_to_py(py, &provider_msg)
}
// ============================================================================
// Conversion functions
// ============================================================================
/// Convert array of Chat Completions messages to Lingua Messages
#[pyfunction]
fn chat_completions_messages_to_lingua<'py>(
py: Python<'py>,
value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
convert_to_lingua::<Vec<ChatCompletionRequestMessageExt>, Vec<Message>>(py, value)
}
/// Convert array of Lingua Messages to Chat Completions messages
#[pyfunction]
fn lingua_to_chat_completions_messages<'py>(
py: Python<'py>,
value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
let messages: Vec<Message> = py_to_rust(py, value)?;
let chat_messages = messages_to_chat_completion_messages(messages).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Conversion error: {:?}", e))
})?;
rust_to_py(py, &chat_messages)
}
/// Convert array of Responses API messages to Lingua Messages
#[pyfunction]
fn responses_messages_to_lingua<'py>(
py: Python<'py>,
value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
convert_to_lingua::<Vec<openai::InputItem>, Vec<Message>>(py, value)
}
/// Convert array of Lingua Messages to Responses API messages
#[pyfunction]
fn lingua_to_responses_messages<'py>(
py: Python<'py>,
value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
convert_from_lingua::<Vec<Message>, Vec<openai::InputItem>>(py, value)
}
/// Convert array of Anthropic messages to Lingua Messages
#[pyfunction]
fn anthropic_messages_to_lingua<'py>(
py: Python<'py>,
value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
let input_messages: Vec<anthropic::InputMessage> = py_to_rust(py, value)?;
let messages = anthropic_input_messages_to_universal_messages(input_messages).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Conversion error: {:?}", e))
})?;
rust_to_py(py, &messages)
}
/// Convert array of Lingua Messages to Anthropic messages
#[pyfunction]
fn lingua_to_anthropic_messages<'py>(
py: Python<'py>,
value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
let messages: Vec<Message> = py_to_rust(py, value)?;
let input_messages = universal_messages_to_anthropic_input_messages(messages).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Conversion error: {:?}", e))
})?;
rust_to_py(py, &input_messages)
}
/// Convert array of Google Content items to Lingua Messages
#[pyfunction]
fn google_contents_to_lingua<'py>(
py: Python<'py>,
value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
convert_to_lingua::<Vec<google::Content>, Vec<Message>>(py, value)
}
/// Convert array of Lingua Messages to Google Content items
#[pyfunction]
fn lingua_to_google_contents<'py>(
py: Python<'py>,
value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
convert_from_lingua::<Vec<Message>, Vec<google::Content>>(py, value)
}
// ============================================================================
// Processing functions
// ============================================================================
/// Deduplicate messages based on role and content
#[pyfunction]
fn deduplicate_messages<'py>(
py: Python<'py>,
value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
use crate::processing::dedup::deduplicate_messages as dedup;
use crate::universal::Message;
// Convert Python value to Vec<Message>
let messages: Vec<Message> = py_to_rust(py, value)?;
// Deduplicate
let deduplicated = dedup(messages);
// Convert back to Python
rust_to_py(py, &deduplicated)
}
/// Import messages from spans
#[pyfunction]
fn import_messages_from_spans<'py>(
py: Python<'py>,
value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
use crate::processing::import::{import_messages_from_spans as import, Span};
// Convert Python value to Vec<Span>
let spans: Vec<Span> = py_to_rust(py, value)?;
// Import messages
let messages = import(spans);
// Convert back to Python
rust_to_py(py, &messages)
}
/// Import and deduplicate messages from spans in a single operation
#[pyfunction]
fn import_and_deduplicate_messages<'py>(
py: Python<'py>,
value: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyAny>> {
use crate::processing::import::{import_and_deduplicate_messages as import_dedup, Span};
// Convert Python value to Vec<Span>
let spans: Vec<Span> = py_to_rust(py, value)?;
// Import and deduplicate messages
let messages = import_dedup(spans);
// Convert back to Python
rust_to_py(py, &messages)
}
// ============================================================================
// Validation functions
// ============================================================================
/// Validate a JSON string as a Chat Completions request
#[pyfunction]
#[cfg(feature = "openai")]
fn validate_chat_completions_request<'py>(
py: Python<'py>,
json: &str,
) -> PyResult<Bound<'py, PyAny>> {
use crate::validation::openai::validate_chat_completions_request as validate;
let result = validate(json)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()))?;
rust_to_py(py, &result)
}
/// Validate a JSON string as a Chat Completions response
#[pyfunction]
#[cfg(feature = "openai")]
fn validate_chat_completions_response<'py>(
py: Python<'py>,
json: &str,
) -> PyResult<Bound<'py, PyAny>> {
use crate::validation::openai::validate_chat_completions_response as validate;
let result = validate(json)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()))?;
rust_to_py(py, &result)
}
/// Validate a JSON string as a Responses API request
#[pyfunction]
#[cfg(feature = "openai")]
fn validate_responses_request<'py>(py: Python<'py>, json: &str) -> PyResult<Bound<'py, PyAny>> {
use crate::validation::openai::validate_responses_request as validate;
let result = validate(json)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()))?;
rust_to_py(py, &result)
}
/// Validate a JSON string as a Responses API response
#[pyfunction]
#[cfg(feature = "openai")]
fn validate_responses_response<'py>(py: Python<'py>, json: &str) -> PyResult<Bound<'py, PyAny>> {
use crate::validation::openai::validate_responses_response as validate;
let result = validate(json)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()))?;
rust_to_py(py, &result)
}
/// Validate a JSON string as an OpenAI request
/// @deprecated Use validate_chat_completions_request instead
#[pyfunction]
#[cfg(feature = "openai")]
fn validate_openai_request<'py>(py: Python<'py>, json: &str) -> PyResult<Bound<'py, PyAny>> {
validate_chat_completions_request(py, json)
}
/// Validate a JSON string as an OpenAI response
/// @deprecated Use validate_chat_completions_response instead
#[pyfunction]
#[cfg(feature = "openai")]
fn validate_openai_response<'py>(py: Python<'py>, json: &str) -> PyResult<Bound<'py, PyAny>> {
validate_chat_completions_response(py, json)
}
/// Validate a JSON string as an Anthropic request
#[pyfunction]
#[cfg(feature = "anthropic")]
fn validate_anthropic_request<'py>(py: Python<'py>, json: &str) -> PyResult<Bound<'py, PyAny>> {
use crate::validation::anthropic::validate_anthropic_request as validate;
let result = validate(json)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()))?;
rust_to_py(py, &result)
}
/// Validate a JSON string as an Anthropic response
#[pyfunction]
#[cfg(feature = "anthropic")]
fn validate_anthropic_response<'py>(py: Python<'py>, json: &str) -> PyResult<Bound<'py, PyAny>> {
use crate::validation::anthropic::validate_anthropic_response as validate;
let result = validate(json)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()))?;
rust_to_py(py, &result)
}
// ============================================================================
// Transform functions
// ============================================================================
/// Transform a request payload to the target format.
///
/// Takes a JSON string and target format, auto-detects the source format,
/// and transforms to the target format.
///
/// Returns a dict with either:
/// - `{ "pass_through": True, "data": ... }` if payload is already valid for target
/// - `{ "transformed": True, "data": ..., "source_format": "..." }` if transformed
#[pyfunction]
#[pyo3(signature = (json, target_format, model=None))]
fn transform_request<'py>(
py: Python<'py>,
json: &str,
target_format: &str,
model: Option<String>,
) -> PyResult<Bound<'py, PyAny>> {
use crate::capabilities::ProviderFormat;
use crate::processing::transform::{transform_request as transform, TransformResult};
use bytes::Bytes;
let target: ProviderFormat = target_format.parse().map_err(|_| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Unknown target format: {}",
target_format
))
})?;
let input_bytes = Bytes::from(json.to_owned());
let result = transform(input_bytes, target, model.as_deref())
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()))?;
match result {
TransformResult::PassThrough(bytes) => {
let data: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Failed to parse result: {}",
e
))
})?;
let dict = pyo3::types::PyDict::new(py);
dict.set_item("pass_through", true)?;
dict.set_item("data", rust_to_py(py, &data)?)?;
Ok(dict.into_any())
}
TransformResult::Transformed {
bytes,
source_format,
..
} => {
let data: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Failed to parse result: {}",
e
))
})?;
let dict = pyo3::types::PyDict::new(py);
dict.set_item("transformed", true)?;
dict.set_item("data", rust_to_py(py, &data)?)?;
dict.set_item("source_format", source_format.to_string())?;
Ok(dict.into_any())
}
}
}
/// Transform a response payload from one format to another.
///
/// Takes a JSON string and target format, auto-detects the source format,
/// and transforms to the target format.
///
/// Returns a dict with either:
/// - `{ "pass_through": True, "data": ... }` if payload is already valid for target
/// - `{ "transformed": True, "data": ..., "source_format": "..." }` if transformed
#[pyfunction]
fn transform_response<'py>(
py: Python<'py>,
json: &str,
target_format: &str,
) -> PyResult<Bound<'py, PyAny>> {
use crate::capabilities::ProviderFormat;
use crate::processing::transform::{transform_response as transform, TransformResult};
use bytes::Bytes;
let target: ProviderFormat = target_format.parse().map_err(|_| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Unknown target format: {}",
target_format
))
})?;
let input_bytes = Bytes::from(json.to_owned());
let result = transform(input_bytes, target)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()))?;
match result {
TransformResult::PassThrough(bytes) => {
let data: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Failed to parse result: {}",
e
))
})?;
let dict = pyo3::types::PyDict::new(py);
dict.set_item("pass_through", true)?;
dict.set_item("data", rust_to_py(py, &data)?)?;
Ok(dict.into_any())
}
TransformResult::Transformed {
bytes,
source_format,
..
} => {
let data: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!(
"Failed to parse result: {}",
e
))
})?;
let dict = pyo3::types::PyDict::new(py);
dict.set_item("transformed", true)?;
dict.set_item("data", rust_to_py(py, &data)?)?;
dict.set_item("source_format", source_format.to_string())?;
Ok(dict.into_any())
}
}
}
/// Extract model name from request without full transformation.
///
/// This is a fast path for routing decisions that only need the model name.
/// Returns the model string if found, or None if not present.
#[pyfunction]
fn extract_model(json: &str) -> Option<String> {
use crate::processing::transform::extract_model as extract;
extract(json.as_bytes())
}
// ============================================================================
// Python module definition
// ============================================================================
/// Python module for Lingua
#[pymodule]
fn _lingua(m: &Bound<'_, PyModule>) -> PyResult<()> {
// Conversion functions
m.add_function(wrap_pyfunction!(chat_completions_messages_to_lingua, m)?)?;
m.add_function(wrap_pyfunction!(lingua_to_chat_completions_messages, m)?)?;
m.add_function(wrap_pyfunction!(responses_messages_to_lingua, m)?)?;
m.add_function(wrap_pyfunction!(lingua_to_responses_messages, m)?)?;
m.add_function(wrap_pyfunction!(anthropic_messages_to_lingua, m)?)?;
m.add_function(wrap_pyfunction!(lingua_to_anthropic_messages, m)?)?;
m.add_function(wrap_pyfunction!(google_contents_to_lingua, m)?)?;
m.add_function(wrap_pyfunction!(lingua_to_google_contents, m)?)?;
// Processing functions
m.add_function(wrap_pyfunction!(deduplicate_messages, m)?)?;
m.add_function(wrap_pyfunction!(import_messages_from_spans, m)?)?;
m.add_function(wrap_pyfunction!(import_and_deduplicate_messages, m)?)?;
// Validation functions
#[cfg(feature = "openai")]
{
m.add_function(wrap_pyfunction!(validate_chat_completions_request, m)?)?;
m.add_function(wrap_pyfunction!(validate_chat_completions_response, m)?)?;
m.add_function(wrap_pyfunction!(validate_responses_request, m)?)?;
m.add_function(wrap_pyfunction!(validate_responses_response, m)?)?;
m.add_function(wrap_pyfunction!(validate_openai_request, m)?)?;
m.add_function(wrap_pyfunction!(validate_openai_response, m)?)?;
}
#[cfg(feature = "anthropic")]
{
m.add_function(wrap_pyfunction!(validate_anthropic_request, m)?)?;
m.add_function(wrap_pyfunction!(validate_anthropic_response, m)?)?;
}
// Transform functions
m.add_function(wrap_pyfunction!(transform_request, m)?)?;
m.add_function(wrap_pyfunction!(transform_response, m)?)?;
m.add_function(wrap_pyfunction!(extract_model, m)?)?;
Ok(())
}