I'm writing a proxy that sits between an AI agent and an OpenAI-compatible API. Replies come back as server-sent events. Text should reach the client the moment it arrives, but as soon as an event could carry a tool call, the proxy has to hold everything back until the whole reply can be checked.

So every event goes through one question: is this event only text? If yes, its original bytes go out unchanged. From the first event that isn't (a tool call, a finish reason, an unknown field, anything that doesn't parse) the rest of the stream is held. It has to fail closed: a field I've never seen must count as unsafe.

Right now I do that by walking serde_json::Value against allowlists (trimmed a little):

const LIVE_CHOICE_FIELDS: [&str; 4] = ["index", "delta", "finish_reason", "logprobs"]; const LIVE_TEXT_FIELDS: [&str; 4] = ["content", "refusal", "reasoning", "reasoning_content"]; fn admit_chat(&mut self, chunk: &Value) -> bool { let Some(choices) = chunk.get("choices").and_then(Value::as_array) else { return false; }; choices.iter().all(|choice| { let Some(fields) = choice.as_object() else { return false }; let known = fields .iter() .all(|(key, value)| LIVE_CHOICE_FIELDS.contains(&key.as_str()) || value.is_null()); let delta_ok = match choice.get("delta") { None | Some(Value::Null) => true, Some(Value::Object(delta)) => delta.iter().all(|(key, value)| match key.as_str() { "role" => value.is_null() || value == "assistant", k if LIVE_TEXT_FIELDS.contains(&k) => value.is_null() || value.is_string(), _ => value.is_null(), // providers send `tool_calls: null` and similar }), Some(_) => false, }; known && delta_ok && choice["finish_reason"].is_null() }) } 

The full version, with the Responses API events and the gate that holds the stream, is here: razorwire/src/sse.rs at 4511ed1e23794e192598bf93d92a40267fdef7e1 · razorwire-dev/razorwire · GitHub

Two questions:

  1. Would typed structs with #[serde(deny_unknown_fields)] be cleaner? What stops me is the "any field is fine if it's null" rule, which I don't see how to express with derives alone.
  2. Can you see a way for a tool call to get past this? For example, JSON that serde_json reads differently from how a client SDK would.

Thanks!

1 post - 1 participant

Read full topic