client_integration.rs 16 KB

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