返回 CodeWhale
deepseek_tools.rs
根目录 / crates / engine / src / client / deepseek_tools.rs
1 use anyhow::{Context, Result, bail};
2 use reqwest::header::CONTENT_TYPE;
3 use serde::{Deserialize, Serialize};
4 use serde_json::{Value, json};
5
6 use codewhale_models::{MessageRequest, Tool};
7
8 use super::CodewhaleClient;
9 use super::prepared::WireDialect;
10 use super::wire::{ERROR_BODY_MAX_BYTES, bounded_error_text, read_bounded_response_bytes};
11
12 pub const DEEPSEEK_WEB_SEARCH_TOOL: &str = "deepseek_web_search";
13 pub const DEEPSEEK_READ_URL_TOOL: &str = "deepseek_read_url";
14 pub(super) const DEEPSEEK_FILE_PARSE_MAX_BYTES: usize = 100 * 1024 * 1024;
15 pub(super) const DEEPSEEK_USER_DATA_MAX_BYTES: usize = 32 * 1024 * 1024;
16 pub(super) const DEEPSEEK_FILE_RESPONSE_MAX_BYTES: usize = 1024 * 1024;
17
18 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19 #[serde(rename_all = "snake_case")]
20 pub enum DeepseekFilesPurpose {
21 TextRecognition,
22 RichLayoutRecognition,
23 UserData,
24 }
25
26 impl DeepseekFilesPurpose {
27 #[must_use]
28 pub const fn as_str(self) -> &'static str {
29 match self {
30 Self::TextRecognition => "text_recognition",
31 Self::RichLayoutRecognition => "rich_layout_recognition",
32 Self::UserData => "user_data",
33 }
34 }
35
36 #[must_use]
37 pub const fn max_upload_bytes(self) -> usize {
38 match self {
39 Self::TextRecognition | Self::RichLayoutRecognition => DEEPSEEK_FILE_PARSE_MAX_BYTES,
40 Self::UserData => DEEPSEEK_USER_DATA_MAX_BYTES,
41 }
42 }
43 }
44
45 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46 pub struct DeepseekUploadedFile {
47 pub id: String,
48 #[serde(default)]
49 pub object: Option<String>,
50 #[serde(default)]
51 pub bytes: Option<u64>,
52 #[serde(default)]
53 pub created_at: Option<u64>,
54 #[serde(default)]
55 pub filename: Option<String>,
56 #[serde(default)]
57 pub purpose: Option<String>,
58 #[serde(default)]
59 pub status: Option<String>,
60 #[serde(default)]
61 pub status_details: Option<Value>,
62 }
63
64 pub(super) fn deepseek_web_tool_kind(tool: &Tool) -> Option<&'static str> {
65 let raw = tool.tool_type.as_deref().unwrap_or(tool.name.as_str());
66 match raw {
67 DEEPSEEK_WEB_SEARCH_TOOL => Some(DEEPSEEK_WEB_SEARCH_TOOL),
68 DEEPSEEK_READ_URL_TOOL => Some(DEEPSEEK_READ_URL_TOOL),
69 _ => None,
70 }
71 }
72
73 pub(super) fn validate_deepseek_web_tools(tools: &[Tool], dialect: WireDialect) -> Result<bool> {
74 let mut saw_search = false;
75 let mut saw_read_url = false;
76 let mut saw_incompatible_responses_tool = None;
77
78 for tool in tools {
79 if let Some(kind) = deepseek_web_tool_kind(tool) {
80 match kind {
81 DEEPSEEK_WEB_SEARCH_TOOL => {
82 if saw_search {
83 bail!("duplicate deepseek_web_search tool declaration");
84 }
85 saw_search = true;
86 }
87 DEEPSEEK_READ_URL_TOOL => {
88 if saw_read_url {
89 bail!("duplicate deepseek_read_url tool declaration");
90 }
91 saw_read_url = true;
92 }
93 _ => {}
94 }
95 if let Some(obj) = tool.input_schema.as_object() {
96 for forbidden in ["allowed_domains", "blocked_domains", "user_location"] {
97 if obj.contains_key(forbidden) {
98 bail!("{kind} does not support `{forbidden}`");
99 }
100 }
101 }
102 } else if dialect == WireDialect::OpenAiResponses
103 && let Some(tool_type) = tool.tool_type.as_deref()
104 && matches!(
105 tool_type,
106 "web_search" | "custom" | "namespace" | "tool_search"
107 )
108 {
109 saw_incompatible_responses_tool = Some(tool_type.to_string());
110 }
111 }
112
113 let has_deepseek_web_tools = saw_search || saw_read_url;
114 if has_deepseek_web_tools && let Some(other) = saw_incompatible_responses_tool {
115 bail!(
116 "cannot combine deepseek_web_search/deepseek_read_url with `{other}` in Responses API"
117 );
118 }
119
120 Ok(has_deepseek_web_tools)
121 }
122
123 pub(super) fn validate_deepseek_web_tool_choice(
124 tool_choice: &Value,
125 has_deepseek_web_tools: bool,
126 ) -> Result<()> {
127 let targeted_name = tool_choice
128 .as_str()
129 .filter(|s| !matches!(*s, "auto" | "none" | "any" | "required"))
130 .or_else(|| {
131 tool_choice
132 .get("type")
133 .and_then(Value::as_str)
134 .filter(|t| matches!(*t, DEEPSEEK_WEB_SEARCH_TOOL | DEEPSEEK_READ_URL_TOOL))
135 })
136 .or_else(|| {
137 let choice_type = tool_choice.get("type").and_then(Value::as_str);
138 if matches!(choice_type, Some("tool" | "function")) || choice_type.is_none() {
139 tool_choice.get("name").and_then(Value::as_str).or_else(|| {
140 tool_choice
141 .pointer("/function/name")
142 .and_then(Value::as_str)
143 })
144 } else {
145 None
146 }
147 });
148
149 if let Some(name) = targeted_name
150 && matches!(name, DEEPSEEK_WEB_SEARCH_TOOL | DEEPSEEK_READ_URL_TOOL)
151 {
152 bail!("tool_choice cannot force `{name}`");
153 }
154
155 if has_deepseek_web_tools
156 && tool_choice
157 .get("type")
158 .and_then(Value::as_str)
159 .is_some_and(|t| t == "web_search")
160 {
161 bail!("tool_choice cannot force `web_search` when deepseek web tools are declared");
162 }
163
164 if has_deepseek_web_tools && tool_choice_is_required(tool_choice) {
165 bail!(
166 "tool_choice cannot require tool execution when deepseek_web_search or deepseek_read_url is declared"
167 );
168 }
169
170 Ok(())
171 }
172
173 fn tool_choice_is_required(tool_choice: &Value) -> bool {
174 tool_choice.as_str() == Some("required")
175 || matches!(
176 tool_choice.get("type").and_then(Value::as_str),
177 Some("required" | "any")
178 )
179 }
180
181 pub(super) fn validate_and_apply_safety_check_and_title(
182 request: &MessageRequest,
183 body: &mut Value,
184 is_deepseek_route: bool,
185 ) -> Result<()> {
186 if !is_deepseek_route {
187 if request.safety_check.is_some() || request.title.is_some() {
188 bail!("safety_check and title are only supported on DeepSeek routes");
189 }
190 return Ok(());
191 }
192 if let Some(safety_check) = request.safety_check.as_ref() {
193 let level = safety_check.level.as_str();
194 if !matches!(level, "low" | "high") {
195 bail!("safety_check.level must be `low` or `high`");
196 }
197 body["safety_check"] = json!({ "level": level });
198 }
199 if let Some(title) = request.title.as_ref() {
200 body["title"] = json!({ "enabled": title.enabled });
201 }
202 Ok(())
203 }
204
205 pub(super) fn deepseek_root_url(base_url: &str) -> String {
206 let trimmed = base_url.trim().trim_end_matches('/');
207 for suffix in ["/anthropic", "/beta", "/v1"] {
208 if let Some(root) = trimmed.strip_suffix(suffix) {
209 return root.to_string();
210 }
211 }
212 trimmed.to_string()
213 }
214
215 fn sanitize_multipart_filename(filename: &str) -> String {
216 let sanitized: String = filename
217 .chars()
218 .map(|ch| {
219 if ch == '"' || ch == '\\' || ch.is_control() {
220 '_'
221 } else {
222 ch
223 }
224 })
225 .collect();
226 if sanitized.trim().is_empty() {
227 "upload.bin".to_string()
228 } else {
229 sanitized
230 }
231 }
232
233 fn is_http_token_char(ch: char) -> bool {
234 ch.is_ascii_alphanumeric()
235 || matches!(
236 ch,
237 '!' | '#'
238 | '$'
239 | '%'
240 | '&'
241 | '\''
242 | '*'
243 | '+'
244 | '-'
245 | '.'
246 | '^'
247 | '_'
248 | '`'
249 | '|'
250 | '~'
251 )
252 }
253
254 fn validate_multipart_mime_type(mime_type: &str) -> Result<&str> {
255 if mime_type.is_empty()
256 || mime_type
257 .chars()
258 .any(|ch| ch.is_control() || ch.is_whitespace() || ch == ';')
259 {
260 bail!("invalid multipart mime_type `{mime_type}`");
261 }
262 let Some((kind, subtype)) = mime_type.split_once('/') else {
263 bail!("invalid multipart mime_type `{mime_type}`");
264 };
265 if kind.is_empty()
266 || subtype.is_empty()
267 || !kind.chars().all(is_http_token_char)
268 || !subtype.chars().all(is_http_token_char)
269 {
270 bail!("invalid multipart mime_type `{mime_type}`");
271 }
272 Ok(mime_type)
273 }
274
275 fn validate_deepseek_upload_size(purpose: DeepseekFilesPurpose, byte_len: usize) -> Result<()> {
276 if byte_len == 0 {
277 bail!("upload_deepseek_file requires non-empty file bytes");
278 }
279 let max_bytes = purpose.max_upload_bytes();
280 if byte_len > max_bytes {
281 bail!(
282 "DeepSeek file upload exceeds {} byte limit for `{}` ({byte_len} bytes)",
283 max_bytes,
284 purpose.as_str()
285 );
286 }
287 Ok(())
288 }
289
290 fn build_multipart_body(
291 boundary: &str,
292 purpose: Option<DeepseekFilesPurpose>,
293 filename: &str,
294 mime_type: &str,
295 bytes: &[u8],
296 ) -> Result<Vec<u8>> {
297 let validated_mime = validate_multipart_mime_type(mime_type)?;
298 let mut body = Vec::with_capacity(bytes.len() + 256);
299 if let Some(purpose) = purpose {
300 body.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
301 body.extend_from_slice(b"Content-Disposition: form-data; name=\"purpose\"\r\n\r\n");
302 body.extend_from_slice(purpose.as_str().as_bytes());
303 body.extend_from_slice(b"\r\n");
304 }
305 let clean_name = sanitize_multipart_filename(filename);
306 body.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
307 body.extend_from_slice(
308 format!("Content-Disposition: form-data; name=\"file\"; filename=\"{clean_name}\"\r\n")
309 .as_bytes(),
310 );
311 body.extend_from_slice(format!("Content-Type: {validated_mime}\r\n\r\n").as_bytes());
312 body.extend_from_slice(bytes);
313 body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
314 Ok(body)
315 }
316
317 impl CodewhaleClient {
318 pub async fn upload_deepseek_file(
319 &self,
320 filename: &str,
321 bytes: Vec<u8>,
322 mime_type: Option<&str>,
323 purpose: DeepseekFilesPurpose,
324 ) -> Result<DeepseekUploadedFile> {
325 validate_deepseek_upload_size(purpose, bytes.len())?;
326 let boundary = format!("cw-ds-{}", uuid::Uuid::new_v4().simple());
327 let mime = mime_type.unwrap_or("application/octet-stream");
328 let payload = build_multipart_body(&boundary, Some(purpose), filename, mime, &bytes)?;
329 let url = format!("{}/files", deepseek_root_url(&self.base_url));
330 let content_type = format!("multipart/form-data; boundary={boundary}");
331 let _inference_permit = self.acquire_remote_control_inference_permit().await;
332 let _request_permit = self.acquire_provider_request_permit().await;
333 let response = self
334 .send_with_retry(|| {
335 self.http_client
336 .post(&url)
337 .header(CONTENT_TYPE, &content_type)
338 .body(payload.clone())
339 })
340 .await
341 .context("DeepSeek Files API upload failed")?;
342
343 let status = response.status();
344 if !status.is_success() {
345 let raw = bounded_error_text(response, ERROR_BODY_MAX_BYTES).await;
346 bail!("DeepSeek Files API returned HTTP {status}: {raw}");
347 }
348 let raw = read_bounded_response_bytes(response, DEEPSEEK_FILE_RESPONSE_MAX_BYTES)
349 .await
350 .context("Failed to read DeepSeek Files API response")?;
351 serde_json::from_slice::<DeepseekUploadedFile>(&raw)
352 .context("Failed to decode DeepSeek Files API response")
353 }
354 }
355
356 #[cfg(test)]
357 mod tests {
358 use super::*;
359 use wiremock::matchers::{method, path};
360 use wiremock::{Mock, MockServer, ResponseTemplate};
361
362 fn deepseek_test_client(base_url: &str) -> CodewhaleClient {
363 let _ = rustls::crypto::ring::default_provider().install_default();
364 let mut config = codewhale_runtime::config::Config::default();
365 config.provider = Some("deepseek".to_string());
366 config.providers = Some(codewhale_runtime::config::ProvidersConfig {
367 deepseek: codewhale_runtime::config::ProviderConfig {
368 api_key: Some("test-key".to_string()),
369 base_url: Some(base_url.to_string()),
370 ..Default::default()
371 },
372 ..Default::default()
373 });
374 CodewhaleClient::new(&config).expect("DeepSeek client constructs")
375 }
376
377 #[tokio::test]
378 async fn upload_deepseek_file_places_purpose_before_file_and_decodes_response() {
379 let server = MockServer::start().await;
380 Mock::given(method("POST"))
381 .and(path("/files"))
382 .respond_with(|req: &wiremock::Request| {
383 let ct = req
384 .headers
385 .get("content-type")
386 .and_then(|v| v.to_str().ok())
387 .unwrap_or("");
388 assert!(ct.starts_with("multipart/form-data; boundary="), "{ct}");
389 let body = String::from_utf8_lossy(&req.body);
390 let purpose_idx = body
391 .find("name=\"purpose\"")
392 .expect("multipart must contain purpose");
393 let file_idx = body
394 .find("name=\"file\"; filename=\"spec.pdf\"")
395 .expect("multipart must contain file");
396 assert!(
397 purpose_idx < file_idx,
398 "purpose field must precede file field in multipart body"
399 );
400 assert!(body.contains("rich_layout_recognition"));
401 ResponseTemplate::new(200).set_body_json(json!({
402 "id": "file_ds_1",
403 "object": "file",
404 "bytes": 11,
405 "filename": "spec.pdf",
406 "purpose": "rich_layout_recognition",
407 "status": "parsed"
408 }))
409 })
410 .expect(1)
411 .mount(&server)
412 .await;
413
414 let client = deepseek_test_client(&server.uri());
415 let uploaded = client
416 .upload_deepseek_file(
417 "spec.pdf",
418 b"%PDF-1.4...".to_vec(),
419 Some("application/pdf"),
420 DeepseekFilesPurpose::RichLayoutRecognition,
421 )
422 .await
423 .expect("upload succeeds");
424 assert_eq!(uploaded.id, "file_ds_1");
425 assert_eq!(uploaded.status.as_deref(), Some("parsed"));
426 }
427
428 #[tokio::test]
429 async fn upload_deepseek_file_rejects_injected_mime_type_and_sanitizes_control_filename() {
430 let server = MockServer::start().await;
431 Mock::given(method("POST"))
432 .and(path("/files"))
433 .respond_with(|req: &wiremock::Request| {
434 let body = String::from_utf8_lossy(&req.body);
435 assert!(body.contains("filename=\"report____?.pdf\""));
436 assert!(!body.contains("filename=\"report\r\n"));
437 ResponseTemplate::new(200).set_body_json(json!({
438 "id": "file_ds_sanitized",
439 "object": "file"
440 }))
441 })
442 .expect(1)
443 .mount(&server)
444 .await;
445
446 let client = deepseek_test_client(&server.uri());
447 for bad_mime in [
448 "application/pdf\r\nX-Injected: true",
449 "text/plain; charset=utf-8",
450 "application/pdf\x00evil",
451 "application/",
452 "invalid",
453 " application/pdf",
454 ] {
455 assert!(
456 client
457 .upload_deepseek_file(
458 "spec.pdf",
459 b"hello".to_vec(),
460 Some(bad_mime),
461 DeepseekFilesPurpose::UserData,
462 )
463 .await
464 .is_err(),
465 "mime `{bad_mime}` must be rejected"
466 );
467 }
468
469 let uploaded = client
470 .upload_deepseek_file(
471 "report\r\n\"\x07?.pdf",
472 b"%PDF-1.4".to_vec(),
473 Some("application/pdf"),
474 DeepseekFilesPurpose::TextRecognition,
475 )
476 .await
477 .expect("control characters in filename are neutralized");
478 assert_eq!(uploaded.id, "file_ds_sanitized");
479 }
480
481 #[tokio::test]
482 async fn upload_deepseek_file_enforces_upload_and_response_byte_limits() {
483 let server = MockServer::start().await;
484 let oversize_body = vec![b'a'; DEEPSEEK_FILE_RESPONSE_MAX_BYTES + 128];
485 Mock::given(method("POST"))
486 .and(path("/files"))
487 .respond_with(ResponseTemplate::new(200).set_body_bytes(oversize_body))
488 .expect(1)
489 .mount(&server)
490 .await;
491
492 let client = deepseek_test_client(&server.uri());
493 let user_data_err = client
494 .upload_deepseek_file(
495 "big.txt",
496 vec![b'x'; DEEPSEEK_USER_DATA_MAX_BYTES + 1],
497 Some("text/plain"),
498 DeepseekFilesPurpose::UserData,
499 )
500 .await
501 .expect_err("user_data over 32 MiB must fail client-side");
502 assert!(user_data_err.to_string().contains("byte limit"));
503
504 assert!(
505 validate_deepseek_upload_size(
506 DeepseekFilesPurpose::RichLayoutRecognition,
507 DEEPSEEK_FILE_PARSE_MAX_BYTES + 1,
508 )
509 .is_err()
510 );
511 assert!(
512 validate_deepseek_upload_size(
513 DeepseekFilesPurpose::TextRecognition,
514 DEEPSEEK_FILE_PARSE_MAX_BYTES,
515 )
516 .is_ok()
517 );
518
519 let response_err = client
520 .upload_deepseek_file(
521 "ok.pdf",
522 b"ok".to_vec(),
523 Some("application/pdf"),
524 DeepseekFilesPurpose::TextRecognition,
525 )
526 .await
527 .expect_err("oversized JSON response must fail bounded reader");
528 assert!(
529 response_err
530 .chain()
531 .any(|cause| cause.to_string().contains("byte limit")),
532 "{response_err:#}"
533 );
534 }
535 }
536
536 lines RUST