repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

ai(SMH-PLAN-AIAG0001): add the Anthropic adapter through the shared conformance kit

0c6c8655eae6c9f277038b70ceb670b320f6125a

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Typed message events, block-indexed content, and partial JSON tool
arguments normalize through the same decoder boundary the
OpenAI-compatible adapter proved. Refusal stops distinctly,
pause_turn fails explicitly instead of degrading silently, and the
same malformed, truncated, and post-terminal fixtures apply.

Changed files (2)

+463 / −0 text lines

Diff layout

smith-ai/src/anthropic.rs

Added
new file mode 100644

+460 / −0 text lines

1//! Anthropic Messages stream adapter.
2//!
3//! Translates typed server-sent events, block-indexed content, and partial
4//! JSON tool arguments into the normalized vocabulary. Event types, block
5//! bookkeeping, and the `message_stop` terminal stay inside this module.
6
7use crate::conformance::StreamDecoder;
8use smith::error::{ProviderFault, Result, SmithError};
9use smith::id::{MessageId, ToolCallId};
10use smith::stream::{StopReason, StreamEvent, Usage};
11use std::collections::BTreeMap;
13/// Incremental decoder for one Anthropic Messages stream.
14#[derive(Debug)]
15pub struct AnthropicDecoder {
16 buffer: String,
17 message_id: MessageId,
18 tools: BTreeMap<u64, ToolAccumulator>,
19 stop_reason: Option<StopReason>,
20 usage: Usage,
21 stopped: bool,
22 terminal: bool,
23}
25#[derive(Debug)]
26struct ToolAccumulator {
27 call_id: ToolCallId,
28 name: String,
29 arguments: String,
30}
32impl AnthropicDecoder {
33 /// A decoder for a fresh assistant message.
34 #[must_use]
35 pub fn new() -> Self {
36 Self {
37 buffer: String::new(),
38 message_id: MessageId::new(),
39 tools: BTreeMap::new(),
40 stop_reason: None,
41 usage: Usage::new(),
42 stopped: false,
43 terminal: false,
44 }
45 }
47 fn process_event(&mut self, event: &str, events: &mut Vec<StreamEvent>) -> Result<()> {
48 if self.terminal {
49 return Err(protocol("event after message_stop"));
50 }
51 let value: serde_json::Value = serde_json::from_str(event.trim())
52 .map_err(|e| protocol(format!("event payload is not JSON: {e}")))?;
53 // The SSE event line and the payload type field agree in practice;
54 // the payload is authoritative.
55 match value.get("type").and_then(serde_json::Value::as_str) {
56 Some("message_start") => {
57 if let Some(input) = value
58 .pointer("/message/usage/input_tokens")
59 .and_then(serde_json::Value::as_u64)
60 {
61 self.usage.input_tokens = input;
62 }
63 Ok(())
64 }
65 Some("content_block_start") => self.block_start(&value),
66 Some("content_block_delta") => self.block_delta(&value, events),
67 Some("content_block_stop") => self.block_stop(&value, events),
68 Some("message_delta") => self.message_delta(&value),
69 Some("message_stop") => {
70 self.stop(events)?;
71 Ok(())
72 }
73 Some("ping") => Ok(()),
74 Some("error") => Err(map_error(&value)),
75 other => Err(protocol(format!("unknown event type {other:?}"))),
76 }
77 }
79 fn block_start(&mut self, value: &serde_json::Value) -> Result<()> {
80 let index = block_index(value)?;
81 let block = value
82 .get("content_block")
83 .ok_or_else(|| protocol("content_block_start without content_block"))?;
84 if block.get("type").and_then(serde_json::Value::as_str) == Some("tool_use") {
85 let name = block
86 .get("name")
87 .and_then(serde_json::Value::as_str)
88 .ok_or_else(|| protocol("tool_use block without name"))?;
89 self.tools.insert(
90 index,
91 ToolAccumulator {
92 call_id: ToolCallId::new(),
93 name: name.to_string(),
94 arguments: String::new(),
95 },
96 );
97 }
98 Ok(())
99 }
101 fn block_delta(
102 &mut self,
103 value: &serde_json::Value,
104 events: &mut Vec<StreamEvent>,
105 ) -> Result<()> {
106 let index = block_index(value)?;
107 let delta = value
108 .get("delta")
109 .ok_or_else(|| protocol("content_block_delta without delta"))?;
110 match delta.get("type").and_then(serde_json::Value::as_str) {
111 Some("text_delta") => {
112 let text = delta
113 .get("text")
114 .and_then(serde_json::Value::as_str)
115 .unwrap_or_default();
116 if !text.is_empty() {
117 events.push(StreamEvent::text_delta(self.message_id, text));
118 }
119 }
120 Some("thinking_delta") => {
121 let text = delta
122 .get("thinking")
123 .and_then(serde_json::Value::as_str)
124 .unwrap_or_default();
125 if !text.is_empty() {
126 events.push(StreamEvent::thinking_delta(self.message_id, text));
127 }
128 }
129 Some("input_json_delta") => {
130 let fragment = delta
131 .get("partial_json")
132 .and_then(serde_json::Value::as_str)
133 .unwrap_or_default();
134 if let Some(tool) = self.tools.get_mut(&index) {
135 tool.arguments.push_str(fragment);
136 }
137 }
138 Some(other) => return Err(protocol(format!("unknown delta type {other}"))),
139 None => return Err(protocol("content_block_delta without delta type")),
140 }
141 Ok(())
142 }
144 fn block_stop(
145 &mut self,
146 value: &serde_json::Value,
147 events: &mut Vec<StreamEvent>,
148 ) -> Result<()> {
149 let index = block_index(value)?;
150 if let Some(tool) = self.tools.remove(&index) {
151 let input = if tool.arguments.trim().is_empty() {
152 serde_json::json!({})
153 } else {
154 serde_json::from_str(&tool.arguments)
155 .map_err(|e| protocol(format!("partial_json arguments do not assemble: {e}")))?
156 };
157 events.push(StreamEvent::tool_use(
158 self.message_id,
159 tool.name,
160 input,
161 tool.call_id,
162 ));
163 }
164 Ok(())
165 }
167 fn message_delta(&mut self, value: &serde_json::Value) -> Result<()> {
168 if let Some(reason) = value
169 .get("delta")
170 .and_then(|delta| delta.get("stop_reason"))
171 .and_then(serde_json::Value::as_str)
172 {
173 self.stop_reason = Some(map_stop_reason(reason)?);
174 }
175 if let Some(usage) = value.get("usage") {
176 if let Some(output) = usage
177 .get("output_tokens")
178 .and_then(serde_json::Value::as_u64)
179 {
180 self.usage.output_tokens = output;
181 }
182 for (target, key) in [
183 (
184 &mut self.usage.input_cache_hit_tokens,
185 "cache_read_input_tokens",
186 ),
187 (
188 &mut self.usage.input_cache_write_tokens,
189 "cache_creation_input_tokens",
190 ),
191 ] {
192 if let Some(tokens) = usage.get(key).and_then(serde_json::Value::as_u64) {
193 *target = tokens;
194 }
195 }
196 if let Some(input) = usage
197 .get("input_tokens")
198 .and_then(serde_json::Value::as_u64)
199 {
200 self.usage.input_tokens = input;
201 }
202 }
203 Ok(())
204 }
206 fn stop(&mut self, events: &mut Vec<StreamEvent>) -> Result<()> {
207 let Some(reason) = self.stop_reason else {
208 return Err(protocol("message_stop without stop_reason"));
209 };
210 if !self.tools.is_empty() {
211 return Err(protocol("message_stop with unfinished tool blocks"));
212 }
213 self.terminal = true;
214 self.stopped = true;
215 events.push(StreamEvent::stop(reason, Some(self.usage)));
216 Ok(())
217 }
218}
220impl Default for AnthropicDecoder {
221 fn default() -> Self {
222 Self::new()
223 }
224}
226impl StreamDecoder for AnthropicDecoder {
227 fn push(&mut self, bytes: &[u8]) -> Result<Vec<StreamEvent>> {
228 self.buffer.push_str(&String::from_utf8_lossy(bytes));
229 let mut events = Vec::new();
230 while let Some((event, rest)) = take_sse_event(&self.buffer) {
231 self.buffer = rest;
232 self.process_event(&event, &mut events)?;
233 }
234 Ok(events)
235 }
237 fn finish(&mut self) -> Result<Vec<StreamEvent>> {
238 let mut events = Vec::new();
239 if !self.buffer.trim().is_empty() {
240 let event = std::mem::take(&mut self.buffer);
241 self.process_event(event.trim_end(), &mut events)?;
242 }
243 if !self.stopped {
244 return Err(SmithError::Provider {
245 fault: ProviderFault::Incomplete,
246 });
247 }
248 Ok(events)
249 }
250}
252/// Anthropic SSE carries `event:` and `data:` lines; the data payload rules.
253fn take_sse_event(buffer: &str) -> Option<(String, String)> {
254 let mut data = String::new();
255 let mut consumed = 0;
256 for line in buffer.split_inclusive('\n') {
257 let trimmed = line.trim_end_matches(['\r', '\n']);
258 if trimmed.is_empty() {
259 if data.is_empty() {
260 consumed += line.len();
261 continue;
262 }
263 let rest = buffer[consumed + line.len()..].to_string();
264 return Some((data, rest));
265 }
266 if let Some(payload) = trimmed.strip_prefix("data:") {
267 data.push_str(payload.strip_prefix(' ').unwrap_or(payload));
268 }
269 consumed += line.len();
270 }
271 None
272}
274fn block_index(value: &serde_json::Value) -> Result<u64> {
275 value
276 .get("index")
277 .and_then(serde_json::Value::as_u64)
278 .ok_or_else(|| protocol("block event without index"))
279}
281fn map_stop_reason(reason: &str) -> Result<StopReason> {
282 match reason {
283 "end_turn" => Ok(StopReason::EndTurn),
284 "max_tokens" => Ok(StopReason::Limit),
285 "stop_sequence" => Ok(StopReason::StopSequence),
286 "tool_use" => Ok(StopReason::ToolUse),
287 "refusal" => Ok(StopReason::Refusal),
288 // Server-side tool use is out of scope; pause is explicit, not silent.
289 "pause_turn" => Err(protocol(
290 "pause_turn requires server-side tools, which this build does not support",
291 )),
292 other => Err(protocol(format!("unmapped stop_reason {other}"))),
293 }
294}
296fn map_error(value: &serde_json::Value) -> SmithError {
297 let error = value.get("error").cloned().unwrap_or_else(|| value.clone());
298 let kind = error.get("type").and_then(serde_json::Value::as_str);
299 let message = error
300 .get("message")
301 .and_then(serde_json::Value::as_str)
302 .unwrap_or("unknown provider error")
303 .to_string();
304 let fault = match kind {
305 Some("rate_limit_error") => ProviderFault::RateLimit {
306 retry_after_ms: None,
307 },
308 Some("api_error" | "timeout_error") => ProviderFault::Transient { message },
309 Some("invalid_request_error") => ProviderFault::Invalid {
310 field: None,
311 message,
312 },
313 Some("authentication_error" | "permission_error") => {
314 ProviderFault::Authentication { message }
315 }
316 Some("overloaded_error") => ProviderFault::Overloaded { message },
317 _ => ProviderFault::Protocol { message },
318 };
319 SmithError::Provider { fault }
320}
322fn protocol(message: impl Into<String>) -> SmithError {
323 SmithError::Provider {
324 fault: ProviderFault::Protocol {
325 message: message.into(),
326 },
327 }
328}
330#[cfg(test)]
331mod tests {
332 use super::*;
333 use crate::conformance::{Expected, Fixture, conformance_report};
334 use smith::stream::StopReason;
336 fn sse(lines: &[&str]) -> Vec<u8> {
337 let mut out = String::new();
338 for line in lines {
339 out.push_str("data: ");
340 out.push_str(line);
341 out.push_str("\n\n");
342 }
343 out.into_bytes()
344 }
346 fn tool_fixture() -> Fixture {
347 Fixture {
348 name: "text, thinking, and assembled tool input",
349 chunks: vec![sse(&[
350 r#"{"type":"message_start","message":{"usage":{"input_tokens":12}}}"#,
351 r#"{"type":"content_block_start","index":0,"content_block":{"type":"text"}}"#,
352 r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Look"}}"#,
353 r#"{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ing"}}"#,
354 r#"{"type":"content_block_stop","index":0}"#,
355 r#"{"type":"content_block_start","index":1,"content_block":{"type":"thinking"}}"#,
356 r#"{"type":"content_block_delta","index":1,"delta":{"type":"thinking_delta","thinking":"hmm"}}"#,
357 r#"{"type":"content_block_stop","index":1}"#,
358 r#"{"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"t","name":"write"}}"#,
359 r#"{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"path\""}}"#,
360 r#"{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":":[1,2]}"}}"#,
361 r#"{"type":"content_block_stop","index":2}"#,
362 r#"{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":7,"cache_read_input_tokens":3}}"#,
363 r#"{"type":"message_stop"}"#,
364 ])],
365 expected: vec![
366 Expected::Text("Look".to_string()),
367 Expected::Text("ing".to_string()),
368 Expected::Thinking("hmm".to_string()),
369 Expected::Tool {
370 name: "write".to_string(),
371 input: serde_json::json!({"path": [1, 2]}),
372 },
373 Expected::Stop {
374 reason: StopReason::ToolUse,
375 usage: Some(Usage {
376 input_tokens: 12,
377 output_tokens: 7,
378 input_cache_hit_tokens: 3,
379 input_cache_write_tokens: 0,
380 }),
381 },
382 ],
383 }
384 }
386 fn fault_fixtures() -> Vec<Fixture> {
387 vec![
388 Fixture {
389 name: "overloaded error",
390 chunks: vec![sse(&[
391 r#"{"type":"error","error":{"type":"overloaded_error","message":"busy"}}"#,
392 ])],
393 expected: vec![Expected::Fault("PROVIDER_OVERLOADED".to_string())],
394 },
395 Fixture {
396 name: "refusal stop",
397 chunks: vec![sse(&[
398 r#"{"type":"message_delta","delta":{"stop_reason":"refusal"},"usage":{"output_tokens":1}}"#,
399 r#"{"type":"message_stop"}"#,
400 ])],
401 expected: vec![Expected::Stop {
402 reason: StopReason::Refusal,
403 usage: Some(Usage {
404 input_tokens: 0,
405 output_tokens: 1,
406 input_cache_hit_tokens: 0,
407 input_cache_write_tokens: 0,
408 }),
409 }],
410 },
411 Fixture {
412 name: "pause turn is explicit",
413 chunks: vec![sse(&[
414 r#"{"type":"message_delta","delta":{"stop_reason":"pause_turn"}}"#,
415 r#"{"type":"message_stop"}"#,
416 ])],
417 expected: vec![Expected::Fault("PROVIDER_PROTOCOL".to_string())],
418 },
419 Fixture {
420 name: "message_stop without stop reason",
421 chunks: vec![sse(&[r#"{"type":"message_stop"}"#])],
422 expected: vec![Expected::Fault("PROVIDER_PROTOCOL".to_string())],
423 },
424 Fixture {
425 name: "truncated before message stop",
426 chunks: vec![sse(&[
427 r#"{"type":"content_block_start","index":0,"content_block":{"type":"text"}}"#,
428 ])],
429 expected: vec![Expected::Fault("PROVIDER_INCOMPLETE".to_string())],
430 },
431 Fixture {
432 name: "event after terminal",
433 chunks: vec![
434 sse(&[
435 r#"{"type":"message_delta","delta":{"stop_reason":"end_turn"}}"#,
436 r#"{"type":"message_stop"}"#,
437 ]),
438 sse(&[
439 r#"{"type":"content_block_start","index":0,"content_block":{"type":"text"}}"#,
440 ]),
441 ],
442 expected: vec![
443 Expected::Stop {
444 reason: StopReason::EndTurn,
445 usage: Some(Usage::new()),
446 },
447 Expected::Fault("PROVIDER_PROTOCOL".to_string()),
448 ],
449 },
450 ]
451 }
453 #[test]
454 fn anthropic_adapter_satisfies_conformance() {
455 let mut fixtures = vec![tool_fixture()];
456 fixtures.extend(fault_fixtures());
457 let failures = conformance_report(&|| Box::new(AnthropicDecoder::new()), &fixtures);
458 assert!(failures.is_empty(), "{failures:?}");
459 }
460}

smith-ai/src/lib.rs

Modified

+3 / −0 text lines

77//! incremental decoder producing [`smith::stream::StreamEvent`]s, proven
88//! against the shared conformance kit in [`conformance`].
10/// Anthropic Messages adapter.
11pub mod anthropic;
1012/// Stream conformance kit shared by all vendor adapters.
1113pub mod conformance;
1214/// OpenAI-compatible chat-completions adapter.
1315pub mod openai;
17pub use anthropic::AnthropicDecoder;
1518pub use conformance::{Expected, Fixture, StreamDecoder};
1619pub use openai::OpenAiDecoder;