Skip to main content

gaze_proxy/adapters/
openai.rs

1use http::Method;
2use serde_json::Value;
3use url::Url;
4
5use crate::adapter::{
6    push_string, push_text_blocks, walk_all_strings, PiiSurface, ProviderAdapter, SseEvent,
7};
8
9#[derive(Clone, Debug)]
10#[non_exhaustive]
11pub struct OpenAiAdapter {
12    upstream: Url,
13}
14
15impl OpenAiAdapter {
16    pub fn new(upstream: Url) -> Self {
17        Self { upstream }
18    }
19}
20
21#[async_trait::async_trait]
22impl ProviderAdapter for OpenAiAdapter {
23    fn name(&self) -> &'static str {
24        "openai"
25    }
26
27    fn matches_path(&self, method: &Method, path: &str) -> bool {
28        method == Method::POST
29            && matches!(
30                path,
31                "/v1/chat/completions" | "/v1/completions" | "/v1/responses"
32            )
33    }
34
35    fn upstream_base(&self) -> &Url {
36        &self.upstream
37    }
38
39    fn request_pii_surfaces<'a>(&self, body: &'a mut Value) -> Vec<PiiSurface<'a>> {
40        let mut surfaces = Vec::new();
41        if let Value::Object(root) = body {
42            for (key, value) in root {
43                match key.as_str() {
44                    "system" => push_string(&mut surfaces, "system", value),
45                    "messages" => {
46                        if let Value::Array(messages) = value {
47                            for (index, message) in messages.iter_mut().enumerate() {
48                                collect_message_surfaces(
49                                    &mut surfaces,
50                                    format!("messages[{index}]"),
51                                    message,
52                                );
53                            }
54                        }
55                    }
56                    "input" => push_text_blocks(&mut surfaces, "input", value),
57                    _ => {}
58                }
59            }
60        }
61        surfaces
62    }
63
64    fn response_pii_surfaces<'a>(&self, body: &'a mut Value) -> Vec<PiiSurface<'a>> {
65        let mut surfaces = Vec::new();
66        if let Value::Object(root) = body {
67            for (key, value) in root {
68                match key.as_str() {
69                    "choices" => {
70                        if let Value::Array(choices) = value {
71                            for (index, choice) in choices.iter_mut().enumerate() {
72                                if let Value::Object(choice) = choice {
73                                    for (choice_key, choice_value) in choice {
74                                        match choice_key.as_str() {
75                                            "message" => collect_message_surfaces(
76                                                &mut surfaces,
77                                                format!("choices[{index}].message"),
78                                                choice_value,
79                                            ),
80                                            "delta" => collect_message_surfaces(
81                                                &mut surfaces,
82                                                format!("choices[{index}].delta"),
83                                                choice_value,
84                                            ),
85                                            _ => {}
86                                        }
87                                    }
88                                }
89                            }
90                        }
91                    }
92                    "output" => walk_all_strings(&mut surfaces, "output".to_string(), value),
93                    _ => {}
94                }
95            }
96        }
97        surfaces
98    }
99
100    fn sse_event_pii_surfaces<'a>(&self, event: &'a mut SseEvent) -> Vec<PiiSurface<'a>> {
101        self.response_pii_surfaces(&mut event.data)
102    }
103}
104
105fn collect_message_surfaces<'a>(
106    surfaces: &mut Vec<PiiSurface<'a>>,
107    prefix: String,
108    message: &'a mut Value,
109) {
110    let Value::Object(map) = message else {
111        return;
112    };
113    for (key, value) in map {
114        match key.as_str() {
115            "content" => push_text_blocks(surfaces, &format!("{prefix}.content"), value),
116            "tool_results" => push_text_blocks(surfaces, &format!("{prefix}.tool_results"), value),
117            "tool_calls" => {
118                if let Value::Array(tool_calls) = value {
119                    for (index, tool_call) in tool_calls.iter_mut().enumerate() {
120                        if let Value::Object(tool_call) = tool_call {
121                            if let Some(Value::Object(function)) = tool_call.get_mut("function") {
122                                if let Some(args) = function.get_mut("arguments") {
123                                    push_string(
124                                        surfaces,
125                                        format!("{prefix}.tool_calls[{index}].function.arguments"),
126                                        args,
127                                    );
128                                }
129                            }
130                        }
131                    }
132                }
133            }
134            _ => {}
135        }
136    }
137}