openai_compat_integration.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. use std::collections::HashMap;
  2. use std::ffi::OsString;
  3. use std::sync::Arc;
  4. use std::sync::{Mutex as StdMutex, OnceLock};
  5. use api::{
  6. ContentBlockDelta, ContentBlockDeltaEvent, ContentBlockStartEvent, ContentBlockStopEvent,
  7. InputContentBlock, InputMessage, MessageRequest, OpenAiCompatClient, OpenAiCompatConfig,
  8. OutputContentBlock, ProviderClient, StreamEvent, ToolChoice, ToolDefinition,
  9. };
  10. use serde_json::json;
  11. use tokio::io::{AsyncReadExt, AsyncWriteExt};
  12. use tokio::net::TcpListener;
  13. use tokio::sync::Mutex;
  14. #[tokio::test]
  15. async fn send_message_uses_openai_compatible_endpoint_and_auth() {
  16. let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
  17. let body = concat!(
  18. "{",
  19. "\"id\":\"chatcmpl_test\",",
  20. "\"model\":\"grok-3\",",
  21. "\"choices\":[{",
  22. "\"message\":{\"role\":\"assistant\",\"content\":\"Hello from Grok\",\"tool_calls\":[]},",
  23. "\"finish_reason\":\"stop\"",
  24. "}],",
  25. "\"usage\":{\"prompt_tokens\":11,\"completion_tokens\":5}",
  26. "}"
  27. );
  28. let server = spawn_server(
  29. state.clone(),
  30. vec![http_response("200 OK", "application/json", body)],
  31. )
  32. .await;
  33. let client = OpenAiCompatClient::new("xai-test-key", OpenAiCompatConfig::xai())
  34. .with_base_url(server.base_url());
  35. let response = client
  36. .send_message(&sample_request(false))
  37. .await
  38. .expect("request should succeed");
  39. assert_eq!(response.model, "grok-3");
  40. assert_eq!(response.total_tokens(), 16);
  41. assert_eq!(
  42. response.content,
  43. vec![OutputContentBlock::Text {
  44. text: "Hello from Grok".to_string(),
  45. }]
  46. );
  47. let captured = state.lock().await;
  48. let request = captured.first().expect("server should capture request");
  49. assert_eq!(request.path, "/chat/completions");
  50. assert_eq!(
  51. request.headers.get("authorization").map(String::as_str),
  52. Some("Bearer xai-test-key")
  53. );
  54. let body: serde_json::Value = serde_json::from_str(&request.body).expect("json body");
  55. assert_eq!(body["model"], json!("grok-3"));
  56. assert_eq!(body["messages"][0]["role"], json!("system"));
  57. assert_eq!(body["tools"][0]["type"], json!("function"));
  58. }
  59. #[tokio::test]
  60. async fn stream_message_normalizes_text_and_multiple_tool_calls() {
  61. let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
  62. let sse = concat!(
  63. "data: {\"id\":\"chatcmpl_stream\",\"model\":\"grok-3\",\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n",
  64. "data: {\"id\":\"chatcmpl_stream\",\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"function\":{\"name\":\"weather\",\"arguments\":\"{\\\"city\\\":\\\"Paris\\\"}\"}},{\"index\":1,\"id\":\"call_2\",\"function\":{\"name\":\"clock\",\"arguments\":\"{\\\"zone\\\":\\\"UTC\\\"}\"}}]}}]}\n\n",
  65. "data: {\"id\":\"chatcmpl_stream\",\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n",
  66. "data: [DONE]\n\n"
  67. );
  68. let server = spawn_server(
  69. state.clone(),
  70. vec![http_response_with_headers(
  71. "200 OK",
  72. "text/event-stream",
  73. sse,
  74. &[("x-request-id", "req_grok_stream")],
  75. )],
  76. )
  77. .await;
  78. let client = OpenAiCompatClient::new("xai-test-key", OpenAiCompatConfig::xai())
  79. .with_base_url(server.base_url());
  80. let mut stream = client
  81. .stream_message(&sample_request(false))
  82. .await
  83. .expect("stream should start");
  84. assert_eq!(stream.request_id(), Some("req_grok_stream"));
  85. let mut events = Vec::new();
  86. while let Some(event) = stream.next_event().await.expect("event should parse") {
  87. events.push(event);
  88. }
  89. assert!(matches!(events[0], StreamEvent::MessageStart(_)));
  90. assert!(matches!(
  91. events[1],
  92. StreamEvent::ContentBlockStart(ContentBlockStartEvent {
  93. content_block: OutputContentBlock::Text { .. },
  94. ..
  95. })
  96. ));
  97. assert!(matches!(
  98. events[2],
  99. StreamEvent::ContentBlockDelta(ContentBlockDeltaEvent {
  100. delta: ContentBlockDelta::TextDelta { .. },
  101. ..
  102. })
  103. ));
  104. assert!(matches!(
  105. events[3],
  106. StreamEvent::ContentBlockStart(ContentBlockStartEvent {
  107. index: 1,
  108. content_block: OutputContentBlock::ToolUse { .. },
  109. })
  110. ));
  111. assert!(matches!(
  112. events[4],
  113. StreamEvent::ContentBlockDelta(ContentBlockDeltaEvent {
  114. index: 1,
  115. delta: ContentBlockDelta::InputJsonDelta { .. },
  116. })
  117. ));
  118. assert!(matches!(
  119. events[5],
  120. StreamEvent::ContentBlockStart(ContentBlockStartEvent {
  121. index: 2,
  122. content_block: OutputContentBlock::ToolUse { .. },
  123. })
  124. ));
  125. assert!(matches!(
  126. events[6],
  127. StreamEvent::ContentBlockDelta(ContentBlockDeltaEvent {
  128. index: 2,
  129. delta: ContentBlockDelta::InputJsonDelta { .. },
  130. })
  131. ));
  132. assert!(matches!(
  133. events[7],
  134. StreamEvent::ContentBlockStop(ContentBlockStopEvent { index: 1 })
  135. ));
  136. assert!(matches!(
  137. events[8],
  138. StreamEvent::ContentBlockStop(ContentBlockStopEvent { index: 2 })
  139. ));
  140. assert!(matches!(
  141. events[9],
  142. StreamEvent::ContentBlockStop(ContentBlockStopEvent { index: 0 })
  143. ));
  144. assert!(matches!(events[10], StreamEvent::MessageDelta(_)));
  145. assert!(matches!(events[11], StreamEvent::MessageStop(_)));
  146. let captured = state.lock().await;
  147. let request = captured.first().expect("captured request");
  148. assert_eq!(request.path, "/chat/completions");
  149. assert!(request.body.contains("\"stream\":true"));
  150. }
  151. #[tokio::test]
  152. async fn provider_client_dispatches_xai_requests_from_env() {
  153. let _lock = env_lock();
  154. let _api_key = ScopedEnvVar::set("XAI_API_KEY", "xai-test-key");
  155. let state = Arc::new(Mutex::new(Vec::<CapturedRequest>::new()));
  156. let server = spawn_server(
  157. state.clone(),
  158. vec![http_response(
  159. "200 OK",
  160. "application/json",
  161. "{\"id\":\"chatcmpl_provider\",\"model\":\"grok-3\",\"choices\":[{\"message\":{\"role\":\"assistant\",\"content\":\"Through provider client\",\"tool_calls\":[]},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":9,\"completion_tokens\":4}}",
  162. )],
  163. )
  164. .await;
  165. let _base_url = ScopedEnvVar::set("XAI_BASE_URL", server.base_url());
  166. let client =
  167. ProviderClient::from_model("grok").expect("xAI provider client should be constructed");
  168. assert!(matches!(client, ProviderClient::Xai(_)));
  169. let response = client
  170. .send_message(&sample_request(false))
  171. .await
  172. .expect("provider-dispatched request should succeed");
  173. assert_eq!(response.total_tokens(), 13);
  174. let captured = state.lock().await;
  175. let request = captured.first().expect("captured request");
  176. assert_eq!(request.path, "/chat/completions");
  177. assert_eq!(
  178. request.headers.get("authorization").map(String::as_str),
  179. Some("Bearer xai-test-key")
  180. );
  181. }
  182. #[derive(Debug, Clone, PartialEq, Eq)]
  183. struct CapturedRequest {
  184. path: String,
  185. headers: HashMap<String, String>,
  186. body: String,
  187. }
  188. struct TestServer {
  189. base_url: String,
  190. join_handle: tokio::task::JoinHandle<()>,
  191. }
  192. impl TestServer {
  193. fn base_url(&self) -> String {
  194. self.base_url.clone()
  195. }
  196. }
  197. impl Drop for TestServer {
  198. fn drop(&mut self) {
  199. self.join_handle.abort();
  200. }
  201. }
  202. async fn spawn_server(
  203. state: Arc<Mutex<Vec<CapturedRequest>>>,
  204. responses: Vec<String>,
  205. ) -> TestServer {
  206. let listener = TcpListener::bind("127.0.0.1:0")
  207. .await
  208. .expect("listener should bind");
  209. let address = listener.local_addr().expect("listener addr");
  210. let join_handle = tokio::spawn(async move {
  211. for response in responses {
  212. let (mut socket, _) = listener.accept().await.expect("accept");
  213. let mut buffer = Vec::new();
  214. let mut header_end = None;
  215. loop {
  216. let mut chunk = [0_u8; 1024];
  217. let read = socket.read(&mut chunk).await.expect("read request");
  218. if read == 0 {
  219. break;
  220. }
  221. buffer.extend_from_slice(&chunk[..read]);
  222. if let Some(position) = find_header_end(&buffer) {
  223. header_end = Some(position);
  224. break;
  225. }
  226. }
  227. let header_end = header_end.expect("headers should exist");
  228. let (header_bytes, remaining) = buffer.split_at(header_end);
  229. let header_text = String::from_utf8(header_bytes.to_vec()).expect("utf8 headers");
  230. let mut lines = header_text.split("\r\n");
  231. let request_line = lines.next().expect("request line");
  232. let path = request_line
  233. .split_whitespace()
  234. .nth(1)
  235. .expect("path")
  236. .to_string();
  237. let mut headers = HashMap::new();
  238. let mut content_length = 0_usize;
  239. for line in lines {
  240. if line.is_empty() {
  241. continue;
  242. }
  243. let (name, value) = line.split_once(':').expect("header");
  244. let value = value.trim().to_string();
  245. if name.eq_ignore_ascii_case("content-length") {
  246. content_length = value.parse().expect("content length");
  247. }
  248. headers.insert(name.to_ascii_lowercase(), value);
  249. }
  250. let mut body = remaining[4..].to_vec();
  251. while body.len() < content_length {
  252. let mut chunk = vec![0_u8; content_length - body.len()];
  253. let read = socket.read(&mut chunk).await.expect("read body");
  254. if read == 0 {
  255. break;
  256. }
  257. body.extend_from_slice(&chunk[..read]);
  258. }
  259. state.lock().await.push(CapturedRequest {
  260. path,
  261. headers,
  262. body: String::from_utf8(body).expect("utf8 body"),
  263. });
  264. socket
  265. .write_all(response.as_bytes())
  266. .await
  267. .expect("write response");
  268. }
  269. });
  270. TestServer {
  271. base_url: format!("http://{address}"),
  272. join_handle,
  273. }
  274. }
  275. fn find_header_end(bytes: &[u8]) -> Option<usize> {
  276. bytes.windows(4).position(|window| window == b"\r\n\r\n")
  277. }
  278. fn http_response(status: &str, content_type: &str, body: &str) -> String {
  279. http_response_with_headers(status, content_type, body, &[])
  280. }
  281. fn http_response_with_headers(
  282. status: &str,
  283. content_type: &str,
  284. body: &str,
  285. headers: &[(&str, &str)],
  286. ) -> String {
  287. let mut extra_headers = String::new();
  288. for (name, value) in headers {
  289. use std::fmt::Write as _;
  290. write!(&mut extra_headers, "{name}: {value}\r\n").expect("header write");
  291. }
  292. format!(
  293. "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\n{extra_headers}content-length: {}\r\nconnection: close\r\n\r\n{body}",
  294. body.len()
  295. )
  296. }
  297. fn sample_request(stream: bool) -> MessageRequest {
  298. MessageRequest {
  299. model: "grok-3".to_string(),
  300. max_tokens: 64,
  301. messages: vec![InputMessage {
  302. role: "user".to_string(),
  303. content: vec![InputContentBlock::Text {
  304. text: "Say hello".to_string(),
  305. }],
  306. }],
  307. system: Some("Use tools when needed".to_string()),
  308. tools: Some(vec![ToolDefinition {
  309. name: "weather".to_string(),
  310. description: Some("Fetches weather".to_string()),
  311. input_schema: json!({
  312. "type": "object",
  313. "properties": {"city": {"type": "string"}},
  314. "required": ["city"]
  315. }),
  316. }]),
  317. tool_choice: Some(ToolChoice::Auto),
  318. stream,
  319. }
  320. }
  321. fn env_lock() -> std::sync::MutexGuard<'static, ()> {
  322. static LOCK: OnceLock<StdMutex<()>> = OnceLock::new();
  323. LOCK.get_or_init(|| StdMutex::new(()))
  324. .lock()
  325. .unwrap_or_else(|poisoned| poisoned.into_inner())
  326. }
  327. struct ScopedEnvVar {
  328. key: &'static str,
  329. previous: Option<OsString>,
  330. }
  331. impl ScopedEnvVar {
  332. fn set(key: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {
  333. let previous = std::env::var_os(key);
  334. std::env::set_var(key, value);
  335. Self { key, previous }
  336. }
  337. }
  338. impl Drop for ScopedEnvVar {
  339. fn drop(&mut self) {
  340. match &self.previous {
  341. Some(value) => std::env::set_var(self.key, value),
  342. None => std::env::remove_var(self.key),
  343. }
  344. }
  345. }