client_integration.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. use std::collections::HashMap;
  2. use std::sync::Arc;
  3. use std::time::Duration;
  4. use api::{
  5. AnthropicClient, ApiError, ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent,
  6. InputContentBlock, InputMessage, MessageDeltaEvent, MessageRequest, OutputContentBlock,
  7. StreamEvent, ToolChoice, ToolDefinition,
  8. };
  9. use serde_json::json;
  10. use telemetry::{ClientIdentity, MemoryTelemetrySink, SessionTracer, TelemetryEvent};
  11. use tokio::io::{AsyncReadExt, AsyncWriteExt};
  12. use tokio::net::TcpListener;
  13. use tokio::sync::Mutex;
  14. #[tokio::test]
  15. async fn send_message_posts_json_and_parses_response() {
  16. let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
  17. let body = concat!(
  18. "{",
  19. "\"id\":\"msg_test\",",
  20. "\"type\":\"message\",",
  21. "\"role\":\"assistant\",",
  22. "\"content\":[{\"type\":\"text\",\"text\":\"Hello from Claude\"}],",
  23. "\"model\":\"claude-3-7-sonnet-latest\",",
  24. "\"stop_reason\":\"end_turn\",",
  25. "\"stop_sequence\":null,",
  26. "\"usage\":{\"input_tokens\":12,\"output_tokens\":4},",
  27. "\"request_id\":\"req_body_123\"",
  28. "}"
  29. );
  30. let server = spawn_server(
  31. state.clone(),
  32. vec![http_response("200 OK", "application/json", body)],
  33. )
  34. .await;
  35. let client = AnthropicClient::new("test-key")
  36. .with_auth_token(Some("proxy-token".to_string()))
  37. .with_base_url(server.base_url());
  38. let response = client
  39. .send_message(&sample_request(false))
  40. .await
  41. .expect("request should succeed");
  42. assert_eq!(response.id, "msg_test");
  43. assert_eq!(response.total_tokens(), 16);
  44. assert_eq!(response.request_id.as_deref(), Some("req_body_123"));
  45. assert_eq!(
  46. response.content,
  47. vec![OutputContentBlock::Text {
  48. text: "Hello from Claude".to_string(),
  49. }]
  50. );
  51. let captured = state.lock().await;
  52. let request = captured.first().expect("server should capture request");
  53. assert_eq!(request.method, "POST");
  54. assert_eq!(request.path, "/v1/messages");
  55. assert_eq!(
  56. request.headers.get("x-api-key").map(String::as_str),
  57. Some("test-key")
  58. );
  59. assert_eq!(
  60. request.headers.get("authorization").map(String::as_str),
  61. Some("Bearer proxy-token")
  62. );
  63. assert_eq!(
  64. request.headers.get("anthropic-version").map(String::as_str),
  65. Some("2023-06-01")
  66. );
  67. assert_eq!(
  68. request.headers.get("user-agent").map(String::as_str),
  69. Some("clawd-code/0.1.0 (rust)")
  70. );
  71. let body: serde_json::Value =
  72. serde_json::from_str(&request.body).expect("request body should be json");
  73. assert_eq!(
  74. body.get("model").and_then(serde_json::Value::as_str),
  75. Some("claude-3-7-sonnet-latest")
  76. );
  77. assert!(body.get("stream").is_none());
  78. assert_eq!(body["tools"][0]["name"], json!("get_weather"));
  79. assert_eq!(body["tool_choice"]["type"], json!("auto"));
  80. }
  81. #[tokio::test]
  82. async fn send_message_applies_request_profile_and_records_telemetry() {
  83. let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
  84. let server = spawn_server(
  85. state.clone(),
  86. vec![http_response_with_headers(
  87. "200 OK",
  88. "application/json",
  89. concat!(
  90. "{",
  91. "\"id\":\"msg_profile\",",
  92. "\"type\":\"message\",",
  93. "\"role\":\"assistant\",",
  94. "\"content\":[{\"type\":\"text\",\"text\":\"ok\"}],",
  95. "\"model\":\"claude-3-7-sonnet-latest\",",
  96. "\"stop_reason\":\"end_turn\",",
  97. "\"stop_sequence\":null,",
  98. "\"usage\":{\"input_tokens\":1,\"output_tokens\":1}",
  99. "}"
  100. ),
  101. &[("request-id", "req_profile_123")],
  102. )],
  103. )
  104. .await;
  105. let sink = Arc::new(MemoryTelemetrySink::default());
  106. let client = AnthropicClient::new("test-key")
  107. .with_base_url(server.base_url())
  108. .with_client_identity(ClientIdentity::new("clawd-code", "9.9.9").with_runtime("rust-cli"))
  109. .with_beta("tools-2026-04-01")
  110. .with_extra_body_param("metadata", json!({"source": "clawd-code"}))
  111. .with_session_tracer(SessionTracer::new("session-telemetry", sink.clone()));
  112. let response = client
  113. .send_message(&sample_request(false))
  114. .await
  115. .expect("request should succeed");
  116. assert_eq!(response.request_id.as_deref(), Some("req_profile_123"));
  117. let captured = state.lock().await;
  118. let request = captured.first().expect("server should capture request");
  119. assert_eq!(
  120. request.headers.get("anthropic-beta").map(String::as_str),
  121. Some("tools-2026-04-01")
  122. );
  123. assert_eq!(
  124. request.headers.get("user-agent").map(String::as_str),
  125. Some("clawd-code/9.9.9 (rust-cli)")
  126. );
  127. let body: serde_json::Value =
  128. serde_json::from_str(&request.body).expect("request body should be json");
  129. assert_eq!(body["metadata"]["source"], json!("clawd-code"));
  130. let events = sink.events();
  131. assert_eq!(events.len(), 4);
  132. assert!(matches!(
  133. &events[0],
  134. TelemetryEvent::HttpRequestStarted {
  135. session_id,
  136. attempt: 1,
  137. method,
  138. path,
  139. ..
  140. } if session_id == "session-telemetry" && method == "POST" && path == "/v1/messages"
  141. ));
  142. assert!(matches!(
  143. &events[1],
  144. TelemetryEvent::SessionTrace(trace) if trace.name == "http_request_started"
  145. ));
  146. assert!(matches!(
  147. &events[2],
  148. TelemetryEvent::HttpRequestSucceeded {
  149. request_id,
  150. status: 200,
  151. ..
  152. } if request_id.as_deref() == Some("req_profile_123")
  153. ));
  154. assert!(matches!(
  155. &events[3],
  156. TelemetryEvent::SessionTrace(trace) if trace.name == "http_request_succeeded"
  157. ));
  158. }
  159. #[tokio::test]
  160. async fn stream_message_parses_sse_events_with_tool_use() {
  161. let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
  162. let sse = concat!(
  163. "event: message_start\n",
  164. "data: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_stream\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-3-7-sonnet-latest\",\"stop_reason\":null,\"stop_sequence\":null,\"usage\":{\"input_tokens\":8,\"output_tokens\":0}}}\n\n",
  165. "event: content_block_start\n",
  166. "data: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_123\",\"name\":\"get_weather\",\"input\":{}}}\n\n",
  167. "event: content_block_delta\n",
  168. "data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"{\\\"city\\\":\\\"Paris\\\"}\"}}\n\n",
  169. "event: content_block_stop\n",
  170. "data: {\"type\":\"content_block_stop\",\"index\":0}\n\n",
  171. "event: message_delta\n",
  172. "data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"tool_use\",\"stop_sequence\":null},\"usage\":{\"input_tokens\":8,\"output_tokens\":1}}\n\n",
  173. "event: message_stop\n",
  174. "data: {\"type\":\"message_stop\"}\n\n",
  175. "data: [DONE]\n\n"
  176. );
  177. let server = spawn_server(
  178. state.clone(),
  179. vec![http_response_with_headers(
  180. "200 OK",
  181. "text/event-stream",
  182. sse,
  183. &[("request-id", "req_stream_456")],
  184. )],
  185. )
  186. .await;
  187. let client = AnthropicClient::new("test-key")
  188. .with_auth_token(Some("proxy-token".to_string()))
  189. .with_base_url(server.base_url());
  190. let mut stream = client
  191. .stream_message(&sample_request(false))
  192. .await
  193. .expect("stream should start");
  194. assert_eq!(stream.request_id(), Some("req_stream_456"));
  195. let mut events = Vec::new();
  196. while let Some(event) = stream
  197. .next_event()
  198. .await
  199. .expect("stream event should parse")
  200. {
  201. events.push(event);
  202. }
  203. assert_eq!(events.len(), 6);
  204. assert!(matches!(events[0], StreamEvent::MessageStart(_)));
  205. assert!(matches!(
  206. events[1],
  207. StreamEvent::ContentBlockStart(ContentBlockStartEvent {
  208. content_block: OutputContentBlock::ToolUse { .. },
  209. ..
  210. })
  211. ));
  212. assert!(matches!(
  213. events[2],
  214. StreamEvent::ContentBlockDelta(ContentBlockDeltaEvent {
  215. delta: ContentBlockDelta::InputJsonDelta { .. },
  216. ..
  217. })
  218. ));
  219. assert!(matches!(events[3], StreamEvent::ContentBlockStop(_)));
  220. assert!(matches!(
  221. events[4],
  222. StreamEvent::MessageDelta(MessageDeltaEvent { .. })
  223. ));
  224. assert!(matches!(events[5], StreamEvent::MessageStop(_)));
  225. match &events[1] {
  226. StreamEvent::ContentBlockStart(ContentBlockStartEvent {
  227. content_block: OutputContentBlock::ToolUse { name, input, .. },
  228. ..
  229. }) => {
  230. assert_eq!(name, "get_weather");
  231. assert_eq!(input, &json!({}));
  232. }
  233. other => panic!("expected tool_use block, got {other:?}"),
  234. }
  235. let captured = state.lock().await;
  236. let request = captured.first().expect("server should capture request");
  237. assert!(request.body.contains("\"stream\":true"));
  238. }
  239. #[tokio::test]
  240. async fn retries_retryable_failures_before_succeeding() {
  241. let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
  242. let server = spawn_server(
  243. state.clone(),
  244. vec![
  245. http_response(
  246. "429 Too Many Requests",
  247. "application/json",
  248. "{\"type\":\"error\",\"error\":{\"type\":\"rate_limit_error\",\"message\":\"slow down\"}}",
  249. ),
  250. http_response(
  251. "200 OK",
  252. "application/json",
  253. "{\"id\":\"msg_retry\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"Recovered\"}],\"model\":\"claude-3-7-sonnet-latest\",\"stop_reason\":\"end_turn\",\"stop_sequence\":null,\"usage\":{\"input_tokens\":3,\"output_tokens\":2}}",
  254. ),
  255. ],
  256. )
  257. .await;
  258. let client = AnthropicClient::new("test-key")
  259. .with_base_url(server.base_url())
  260. .with_retry_policy(2, Duration::from_millis(1), Duration::from_millis(2));
  261. let response = client
  262. .send_message(&sample_request(false))
  263. .await
  264. .expect("retry should eventually succeed");
  265. assert_eq!(response.total_tokens(), 5);
  266. assert_eq!(state.lock().await.len(), 2);
  267. }
  268. #[tokio::test]
  269. async fn surfaces_retry_exhaustion_for_persistent_retryable_errors() {
  270. let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
  271. let server = spawn_server(
  272. state.clone(),
  273. vec![
  274. http_response(
  275. "503 Service Unavailable",
  276. "application/json",
  277. "{\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"busy\"}}",
  278. ),
  279. http_response(
  280. "503 Service Unavailable",
  281. "application/json",
  282. "{\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"still busy\"}}",
  283. ),
  284. ],
  285. )
  286. .await;
  287. let client = AnthropicClient::new("test-key")
  288. .with_base_url(server.base_url())
  289. .with_retry_policy(1, Duration::from_millis(1), Duration::from_millis(2));
  290. let error = client
  291. .send_message(&sample_request(false))
  292. .await
  293. .expect_err("persistent 503 should fail");
  294. match error {
  295. ApiError::RetriesExhausted {
  296. attempts,
  297. last_error,
  298. } => {
  299. assert_eq!(attempts, 2);
  300. assert!(matches!(
  301. *last_error,
  302. ApiError::Api {
  303. status: reqwest::StatusCode::SERVICE_UNAVAILABLE,
  304. retryable: true,
  305. ..
  306. }
  307. ));
  308. }
  309. other => panic!("expected retries exhausted, got {other:?}"),
  310. }
  311. }
  312. #[tokio::test]
  313. #[ignore = "requires ANTHROPIC_API_KEY and network access"]
  314. async fn live_stream_smoke_test() {
  315. let client = AnthropicClient::from_env().expect("ANTHROPIC_API_KEY must be set");
  316. let mut stream = client
  317. .stream_message(&MessageRequest {
  318. model: std::env::var("ANTHROPIC_MODEL")
  319. .unwrap_or_else(|_| "claude-3-7-sonnet-latest".to_string()),
  320. max_tokens: 32,
  321. messages: vec![InputMessage::user_text(
  322. "Reply with exactly: hello from rust",
  323. )],
  324. system: None,
  325. tools: None,
  326. tool_choice: None,
  327. stream: false,
  328. })
  329. .await
  330. .expect("live stream should start");
  331. while let Some(_event) = stream
  332. .next_event()
  333. .await
  334. .expect("live stream should yield events")
  335. {}
  336. }
  337. #[derive(Debug, Clone, PartialEq, Eq)]
  338. struct CapturedRequest {
  339. method: String,
  340. path: String,
  341. headers: HashMap<String, String>,
  342. body: String,
  343. }
  344. struct TestServer {
  345. base_url: String,
  346. join_handle: tokio::task::JoinHandle<()>,
  347. }
  348. impl TestServer {
  349. fn base_url(&self) -> String {
  350. self.base_url.clone()
  351. }
  352. }
  353. impl Drop for TestServer {
  354. fn drop(&mut self) {
  355. self.join_handle.abort();
  356. }
  357. }
  358. async fn spawn_server(
  359. state: Arc<Mutex<Vec<CapturedRequest>>>,
  360. responses: Vec<String>,
  361. ) -> TestServer {
  362. let listener = TcpListener::bind("127.0.0.1:0")
  363. .await
  364. .expect("listener should bind");
  365. let address = listener
  366. .local_addr()
  367. .expect("listener should have local addr");
  368. let join_handle = tokio::spawn(async move {
  369. for response in responses {
  370. let (mut socket, _) = listener.accept().await.expect("server should accept");
  371. let mut buffer = Vec::new();
  372. let mut header_end = None;
  373. loop {
  374. let mut chunk = [0_u8; 1024];
  375. let read = socket
  376. .read(&mut chunk)
  377. .await
  378. .expect("request read should succeed");
  379. if read == 0 {
  380. break;
  381. }
  382. buffer.extend_from_slice(&chunk[..read]);
  383. if let Some(position) = find_header_end(&buffer) {
  384. header_end = Some(position);
  385. break;
  386. }
  387. }
  388. let header_end = header_end.expect("request should include headers");
  389. let (header_bytes, remaining) = buffer.split_at(header_end);
  390. let header_text =
  391. String::from_utf8(header_bytes.to_vec()).expect("headers should be utf8");
  392. let mut lines = header_text.split("\r\n");
  393. let request_line = lines.next().expect("request line should exist");
  394. let mut parts = request_line.split_whitespace();
  395. let method = parts.next().expect("method should exist").to_string();
  396. let path = parts.next().expect("path should exist").to_string();
  397. let mut headers = HashMap::new();
  398. let mut content_length = 0_usize;
  399. for line in lines {
  400. if line.is_empty() {
  401. continue;
  402. }
  403. let (name, value) = line.split_once(':').expect("header should have colon");
  404. let value = value.trim().to_string();
  405. if name.eq_ignore_ascii_case("content-length") {
  406. content_length = value.parse().expect("content length should parse");
  407. }
  408. headers.insert(name.to_ascii_lowercase(), value);
  409. }
  410. let mut body = remaining[4..].to_vec();
  411. while body.len() < content_length {
  412. let mut chunk = vec![0_u8; content_length - body.len()];
  413. let read = socket
  414. .read(&mut chunk)
  415. .await
  416. .expect("body read should succeed");
  417. if read == 0 {
  418. break;
  419. }
  420. body.extend_from_slice(&chunk[..read]);
  421. }
  422. state.lock().await.push(CapturedRequest {
  423. method,
  424. path,
  425. headers,
  426. body: String::from_utf8(body).expect("body should be utf8"),
  427. });
  428. socket
  429. .write_all(response.as_bytes())
  430. .await
  431. .expect("response write should succeed");
  432. }
  433. });
  434. TestServer {
  435. base_url: format!("http://{address}"),
  436. join_handle,
  437. }
  438. }
  439. fn find_header_end(bytes: &[u8]) -> Option<usize> {
  440. bytes.windows(4).position(|window| window == b"\r\n\r\n")
  441. }
  442. fn http_response(status: &str, content_type: &str, body: &str) -> String {
  443. http_response_with_headers(status, content_type, body, &[])
  444. }
  445. fn http_response_with_headers(
  446. status: &str,
  447. content_type: &str,
  448. body: &str,
  449. headers: &[(&str, &str)],
  450. ) -> String {
  451. let mut extra_headers = String::new();
  452. for (name, value) in headers {
  453. use std::fmt::Write as _;
  454. write!(&mut extra_headers, "{name}: {value}\r\n").expect("header write should succeed");
  455. }
  456. format!(
  457. "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\n{extra_headers}content-length: {}\r\nconnection: close\r\n\r\n{body}",
  458. body.len()
  459. )
  460. }
  461. fn sample_request(stream: bool) -> MessageRequest {
  462. MessageRequest {
  463. model: "claude-3-7-sonnet-latest".to_string(),
  464. max_tokens: 64,
  465. messages: vec![InputMessage {
  466. role: "user".to_string(),
  467. content: vec![
  468. InputContentBlock::Text {
  469. text: "Say hello".to_string(),
  470. },
  471. InputContentBlock::ToolResult {
  472. tool_use_id: "toolu_prev".to_string(),
  473. content: vec![api::ToolResultContentBlock::Json {
  474. value: json!({"forecast": "sunny"}),
  475. }],
  476. is_error: false,
  477. },
  478. ],
  479. }],
  480. system: Some("Use tools when needed".to_string()),
  481. tools: Some(vec![ToolDefinition {
  482. name: "get_weather".to_string(),
  483. description: Some("Fetches the weather".to_string()),
  484. input_schema: json!({
  485. "type": "object",
  486. "properties": {"city": {"type": "string"}},
  487. "required": ["city"]
  488. }),
  489. }]),
  490. tool_choice: Some(ToolChoice::Auto),
  491. stream,
  492. }
  493. }