技能图谱SKILLSGROVE
技能图谱/办公文档/sarvamai/skills/doc-ai

doc-ai

安装

$npx skills add https://github.com/sarvamai/skills --skill doc-ai
$git clone --depth 1 https://github.com/sarvamai/skills.git /tmp/skills && mkdir -p ~/.claude/skills && cp -r /tmp/skills/doc-ai ~/.claude/skills/doc-ai
请帮我安装这个 Agent Skill:https://github.com/sarvamai/skills/tree/a9bab6a8cda76961fe4e1d80e0e65745d20c01ea/doc-ai ,先阅读它的 SKILL.md 和脚本,确认安全后再安装到我的技能目录。

简介

原文描述 · Apache-2.0Write correct Sarvam Document AI code (Sarvam Vision) — the doc_ai.parse() / .extract() / .classify() / .split() job lifecycle for OCR, table conversion, schema-based field extraction, document classification, and splitting multi-document PDFs, from PDFs, images, and scanned documents. Use this skill when building document digitization, structured-data extraction, document routing/triage, or RAG-ingestion pipelines in Python or JS/TS. Not for translating a document's content into another language — use translate/document for that. For live document intelligence in chat via MCP, use sarvam-mcp instead.
以下 SKILL.md 内容转载自 sarvamai/skills(提交 a9bab6a),依据 Apache-2.0 许可证转载正文(文字未改动;仅省略文件头元数据、将图片显示为链接,超长内容会截断);版权归 owner or entity authorized by 所有。许可证:LICENSE。仅展示说明文件,附带脚本请在原仓库查看。

Document AI — Sarvam Vision

Live in-chat document work → sarvam-mcp (sarvam_tools_vision_parse / _extract / _classify / _split). This skill = SDK code.

Deciding yes/no, a label or a score about text you already have (not a file)? → prism (client.decisions.create). doc_ai.classify() here is for PDF/image files.

Translating a document into another language? → translate/document — a different API (client.document_translation.*), not this one.

SDK floor for the code below: Python sarvamai>=0.1.40, JS sarvamai@>=1.1.13. Older versions have doc_ai.digitise() instead of parse() and no classify()/split().

[!IMPORTANT] Auth: api-subscription-key header — NOT Authorization: Bearer. Base URL: https://api.sarvam.ai (NOT /v1 — that prefix is only for the OpenAI-compatible chat endpoint)

What this API does

Sarvam Vision is a 3B-parameter document-intelligence model, exposed through the Document AI API (SDK group: doc_ai / docAi). Four job types share one lifecycle (create → poll → fetch):

Job What it returns Best for
Parse (doc_ai.parse) Full-page OCR: text + layout + tables, as HTML, Markdown, or JSON Archival, search, RAG ingestion
Extract (doc_ai.extract) Only the fields you define, as structured JSON/CSV/XLSX KYC, invoices, forms
Classify (doc_ai.classify) A label per document (or per page) from categories you define, or a suggested type Routing, triage
Split (doc_ai.split) A multi-document PDF divided into child documents with original page numbers Scanned bundles, mixed batches

Parse and Extract fetch output with get_download_url / get_results; Classify and Split use a different call shape (a JSON request object, see below) and fetch with get_results.

Supports PDF, PNG, JPG, and ZIP (flat archive of page images) across 23 languages (22 Indian + English).

Quick Start — Parse (Python)

import os, time
from sarvamai import SarvamAI

client = SarvamAI(api_subscription_key=os.environ["SARVAM_API_KEY"])

# `file` is a list of (filename, fileobj, content_type) tuples — even for one document
with open("document.pdf", "rb") as f:
    job = client.doc_ai.parse(
        file=[("document.pdf", f, "application/pdf")],
        language="hi-IN",
        # `parse()` has no output_format kwarg (output is HTML by default) — send it as a raw form field:
        request_options={"additional_body_parameters": {"output_format": "md"}},   # "html", "md", or "json"
    )

TERMINAL = {"completed", "partially_completed", "failed", "rejected"}
while True:
    st = client.doc_ai.get_status(job_id=job.job_id)
    if st.status.lower() in TERMINAL:
        break
    time.sleep(5)

dl = client.doc_ai.get_download_url(job_id=job.job_id)
print("download:", dl.method, dl.url)   # a ZIP: primary file + per-page metadata JSON

Quick Start — Parse (JavaScript/TypeScript)

import fs from "fs";
import { SarvamAIClient } from "sarvamai";

const client = new SarvamAIClient({ apiSubscriptionKey: process.env.SARVAM_API_KEY });

// `file` is an array, even for one document
// `parse()` has no output_format option in JS — output is HTML. For md/json, POST /doc-ai/v1/job/parse
// directly with an `output_format` form field.
const job = await client.docAi.parse({
  file: [fs.createReadStream("document.pdf")],
  language: "hi-IN",
});

const TERMINAL = new Set(["completed", "partially_completed", "failed", "rejected"]);
let st;
while (true) {
  st = await client.docAi.getStatus(job.job_id);   // positional — NOT { job_id }
  if (TERMINAL.has(st.status.toLowerCase())) break;
  await new Promise((resolve) => setTimeout(resolve, 5000));
}

const dl = await client.docAi.getDownloadUrl(job.job_id);   // also positional
console.log("download:", dl.method, dl.url);

Extract (schema-based fields)

Same lifecycle, but pass a schema (or a saved config_id) alongside the file:

import json
schema = {
    "type": "object",
    "properties": {
        "policy_number": {"type": "string", "description": "Insurance policy number"},
        "sum_insured":   {"type": "number", "description": "Total sum insured, in INR"},
    },
}

with open("insurance-policy.pdf", "rb") as f:
    job = client.doc_ai.extract(
        file=[("insurance-policy.pdf", f, "application/pdf")],
        schema=json.dumps(schema),   # JSON string, not a dict — or pass config_id="cfg_abc123" instead
        language="en-IN",
        output_format="json",
    )
# ... poll get_status() same as above, then:
results = client.doc_ai.get_results(job_id=job.job_id)
print(results.result)   # {"policy_number": ..., "sum_insured": ...}

Classify and Split

Both take the file(s) plus a required request object that holds the options. They return an acceptance object (status="accepted"), then you poll and fetch get_results.

cats = [
    {"type": "invoice", "description": "A supplier bill with totals and payment details."},
    {"type": "bank_statement", "description": "A bank account statement."},
]

# Classify — scope "document" (default) gives one label; "page" gives one per page
with open("bundle.pdf", "rb") as f:
    job = client.doc_ai.classify(
        file=[("bundle.pdf", f, "application/pdf")],
        request={"config": {"scope": "page", "categories": cats}},
    )

# Split — methods: "semantic" (default), "fixed_pages", "page_ranges", "triggers"
with open("bundle.pdf", "rb") as f:
    job = client.doc_ai.split(
        file=[("bundle.pdf", f, "application/pdf")],
        request={"config": {"method": "semantic", "classify_segments": True, "categories": cats}},
    )

# ... poll get_status() as above, then:
r = client.doc_ai.get_results(job_id=job.job_id)          # include="details" adds pages/evidence
for seg in r.result.segments:                              # Split
    print(seg.pages, seg.type, seg.review_required)
# Classify: r.result.type (scope "document") or r.result.decisions[i].type / .input_page (scope "page")
const job = await client.docAi.split({
  file: [fs.createReadStream("bundle.pdf")],
  request: { config: { method: "fixed_pages", pages_per_segment: 2, classify_segments: false } },
});
// ... poll getStatus(job.job_id), then:
const r: any = await client.docAi.getResults(job.job_id, { include: "details" });
console.log(r.result.segments.map((s: any) => [s.pages, s.type]));

Gotchas

Gotcha Detail
file is always a list Even for a single document: file=[(name, fileobj, content_type)] (Python) / file: [stream] (JS). A bare stream in JS fails with TypeError: request.file is not iterable.
job_id is positional in JS getStatus(job.job_id), getDownloadUrl(job.job_id), getResults(job.job_id) — NOT getStatus({ job_id }). Passing an object sends [object Object] as the path segment and the service rejects it as a non-UUID. Python keeps the kwarg form: get_status(job_id=...).
schema is a JSON string Sent as a multipart form field: json.dumps(schema) in Python, JSON.stringify(schema) in JS — not a raw object/dict.
JS uses wire names, not camelCase Unlike the rest of the JS SDK, doc_ai params/fields are snake_case on the wire: output_format (not outputFormat), job_id, pages_processed. Only the method names (parse, getStatus) are camelCased.
language, not language_code Document AI takes language. Passing language_code (the STT/translate convention) is silently ignored.
output_format values "html" (default), "md", or "json" for Parse; "json" (default), "csv", or "xlsx" for Extract. "markdown" returns 400 — use "md". The SDK's parse() does not expose the field: Python needs request_options={"additional_body_parameters": {...}}; JS silently returns HTML (use REST for md/json). extract() takes output_format normally.
Don't use get_results for Parse jobs Parse output comes from get_download_url (a ZIP). In Python get_results() on a Parse job raises a pydantic ValidationError — the API tags it type: "digitise", which the SDK's result union doesn't accept. get_results is for Extract, Classify and Split.
Classify/Split need request, and config is required classify(file=...) without request={"config": {...}} fails with 400 missing property 'config'. To let the API suggest a document type, send request={"config": {}}. In JS, request is a property of the options object next to file.
Don't use execution: "auto" via the SDK The API answers with 200 and the finished results body, but the SDK types the response as the 201 accepted object. Python raises ValidationError (the job was still created — you lose its job_id); JS returns the results at runtime but typed as if status_url/results_url exist. Submit normally and poll.
Split: set classify_segments deliberately It defaults to true and then requires categories — omitting them returns 400 at '/config': missing property 'categories'. Pass "classify_segments": False when you are not supplying categories. Segments come back with type: None and classification_status: "not_requested" in that case.
Split triggers: match takes equals / prefix / regex Not text: {"type": "text", "match": {"text": "INVOICE"}} returns 400 additional properties 'text' not allowed. Use {"type": "text", "match": {"prefix": "INVOICE"}}. Each marker page starts a new document.
Classify a bundle → type is null A file containing several documents returns classification_status: "mixed", type: null, and MULTIPLE_DOCUMENTS_DETECTED in review_reasons — not a wrong label. Split first, or use scope: "page".
completed ≠ trustworthy For Classify and Split, check review_required (and each segment's review_required) before acting on a label. confidence can be null.
Idempotency key Python idempotency_key="..."; JS "Idempotency-Key": "..." in the options object. Same key + same request returns the same job_id (idempotency_replayed: true); same key + a changed request raises 409 ConflictError.
10-page cap (Parse/Extract) PDF and ZIP uploads are capped at 10 pages/images per job — exceeding it returns 400 invalid_request_error. Split larger documents before uploading.
Legacy document_intelligence group document_intelligence.create_job()/upload_file()/start()/wait_until_complete()/download_output() still works for existing integrations, but new code should use doc_ai.parse()/.extract() — one call creates and submits the job, no separate upload/start step.
Terminal states completed, partially_completed, failed, rejected. Only fetch output/results when completed or partially_completed. Classify/Split jobs start as accepted.
digitise was renamed parse Python 0.1.40 / JS 1.1.13 removed doc_ai.digitise() / docAi.digitise() in favour of parse(); params are otherwise unchanged. The REST path is /doc-ai/v1/job/parse (/digitise still answers).

Full Docs

Fetch schema rules, table-extraction details, and rate limits from:

查看许可证全文(Apache-2.0)
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work.

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   Copyright 2026 Sarvam AI

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.