PAYATHON 2026

Docling Serve API 用 Ruby 请求时只返回默认 Markdown

数据小陈

结论

Docling Serve API 本身支持在一次调用中返回多个格式。只拿到 md_content 时,常见问题出在 Ruby 端 multipart/form-data 的编码,和 curl 的发送方式不一致。curl 用两个 -F 'to_formats=...' 发出两个同名表单字段;HTTParty/Faraday 对 to_formats: ['html', 'json'] 这样的数组值,不一定会编码成重复的 to_formats 字段。服务端没识别出列表,就会回退到默认 Markdown。

原因

  • /v1/convert/file 期望接收 multipart 表单字段;列表参数通常要写成重复字段名:
    to_formats=html
    to_formats=json
    
  • Ruby 的 Hash 中数组值在 multipart 里可能被编码成 to_formats[]=html&to_formats[]=json、JSON 字符串或单个字段;这些形式不符合 Docling 解析的 List[OutputFormat]。
  • 手动设置 Content-Type: multipart/form-data 但缺少 boundary,也会让服务端无法正确解析表单。
  • 单格式字符串 to_formats: 'html' 能成功,说明 URL、文件字段和基本参数名没有问题,问题集中在多值字段编码。

解决步骤

  1. 不要手动写死 Content-Type: multipart/form-data,用 multipart 构造器生成带 boundary 的请求。
  2. 显式构造两个同名的 to_formats 表单字段,不要传 Ruby 数组让库自动推断。
  3. 文件字段名保留 files,并携带 PDF 的 content type。
  4. 发送后抓包或打印请求体,确认里面有两个 name="to_formats" 字段,且 Content-Type 带 boundary=...。

代码示例:Faraday + http/form_data

安装依赖:

gem install http-form_data

示例:

require 'faraday'
require 'http/form_data'

pdf_path = '<PDF filename>.pdf'
docling_url = 'http://127.0.0.1:5001/v1/convert/file'

form = HTTP::FormData.create([
  ['files', HTTP::FormData::File.new(pdf_path, content_type: 'application/pdf')],
  ['from_formats', 'pdf'],
  ['force_ocr', 'false'],
  ['image_export_mode', 'placeholder'],
  ['to_formats', 'html'],
  ['to_formats', 'json']
])

response = Faraday.post(docling_url) do |req|
  req.headers['Accept'] = 'application/json'
  req.headers['Content-Type'] = form.content_type
  req.body = form.to_s
end

puts response.status
puts response.body

如果继续使用 HTTParty,可以复用上面构造好的 form,把原始 body 和带 boundary 的 Content-Type 交给 HTTParty:

require 'httparty'

response = HTTParty.post(
  docling_url,
  headers: {
    'Accept' => 'application/json',
    'Content-Type' => form.content_type
  },
  body: form.to_s
)

puts response.status
puts response.body

注意事项

  • 不要传 to_formats[]=html 或 to_formats=["html","json"];服务端需要的是重复的 to_formats 字段。
  • force_ocr 在 multipart 中建议用字符串 'false',与 curl 的 -F 'force_ocr=false' 保持一致。
  • 返回多格式时,成功响应中应同时出现 html_content、json_content 等字段;如果仍然只有 md_content,优先检查请求体里的字段名和 boundary。
  • 不同 Docling Serve 版本的参数名和返回字段可能略有差异,实际以所运行镜像的接口文档为准。

备注:内容仅供参考。