> ## Documentation Index
> Fetch the complete documentation index at: https://veniceai-docs-revamp.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 文件输入

> 通过 Venice API 向聊天模型发送文档和源文件

文件输入允许您将文档和源文件直接附加到 `/chat/completions` 请求中。Venice 在将其发送到所选模型之前会将文件提取为文本，因此您可以提问、总结、比较或转换文件内容，而无需先构建自己的解析器。

当您的 prompt 取决于文档、电子表格、markdown 文件、JSON 文件或代码文件的内容时，请使用文件输入。它们是请求作用域的输入，而非持久文件存储，因此在每个需要的请求中都包含该文件。

<Info>
  文件输入使用 OpenAI 兼容的聊天 content 数组。添加一个 `type: "file"` 的内容块，并在 `file.file_data` 中提供文件内容。
</Info>

## 支持的文件类型

聊天 API 接受文件输入，可以是 base64 data URL 或公开可访问的 URL。

每个文件的最大尺寸为 **25MB**，在解码 base64 data URL 后或获取 URL 后衡量。

| 类别    | 格式                                                                                           |
| ----- | -------------------------------------------------------------------------------------------- |
| 文档    | PDF、DOCX、PPTX                                                                                |
| 电子表格  | XLSX、XLS、CSV                                                                                 |
| 文本和数据 | TXT、Markdown、JSON                                                                            |
| 源代码   | 大多数常见代码文件，包括 `.py`、`.js`、`.ts`、`.c`、`.cpp`、`.java`、`.go`、`.rs`、`.ps1`、`.sh`、`.yaml` 和 `.sql` |

<Note>
  文件在推理前被提取为文本。提取的文本计入模型的输入上下文，因此请选择具有足够 `availableContextTokens` 来容纳文件、您的指令和预期答案的模型。
</Note>

## 基本用法

发送一个 `messages` 数组，其中 user 消息的 `content` 是文本和文件块的数组：

<CodeGroup>
  ```python Python theme={"dark"}
  import base64
  import os
  from pathlib import Path

  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ["VENICE_API_KEY"],
      base_url="https://api.venice.ai/api/v1",
  )

  path = Path("q3-report.pdf")
  file_data = "data:application/pdf;base64," + base64.b64encode(path.read_bytes()).decode("utf-8")

  response = client.chat.completions.create(
      model="openai-gpt-55",
      messages=[
          {
              "role": "user",
              "content": [
                  {
                      "type": "text",
                      "text": "Summarize this report in five bullets and list the main risks.",
                  },
                  {
                      "type": "file",
                      "file": {
                          "file_data": file_data,
                          "filename": "q3-report.pdf",
                      },
                  },
              ],
          }
      ],
  )

  print(response.choices[0].message.content)
  ```

  ```javascript Node.js theme={"dark"}
  import OpenAI from "openai";
  import { readFile } from "node:fs/promises";

  const client = new OpenAI({
    apiKey: process.env.VENICE_API_KEY,
    baseURL: "https://api.venice.ai/api/v1",
  });

  const pdf = await readFile("q3-report.pdf");
  const fileData = `data:application/pdf;base64,${pdf.toString("base64")}`;

  const response = await client.chat.completions.create({
    model: "openai-gpt-55",
    messages: [
      {
        role: "user",
        content: [
          {
            type: "text",
            text: "Summarize this report in five bullets and list the main risks.",
          },
          {
            type: "file",
            file: {
              file_data: fileData,
              filename: "q3-report.pdf",
            },
          },
        ],
      },
    ],
  });

  console.log(response.choices[0].message.content);
  ```

  ```bash cURL theme={"dark"}
  PDF_BASE64=$(base64 < q3-report.pdf | tr -d '\n')

  curl https://api.venice.ai/api/v1/chat/completions \
    -H "Authorization: Bearer $VENICE_API_KEY" \
    -H "Content-Type: application/json" \
    -d @- <<EOF
  {
    "model": "openai-gpt-55",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "Summarize this report in five bullets and list the main risks."
          },
          {
            "type": "file",
            "file": {
              "file_data": "data:application/pdf;base64,$PDF_BASE64",
              "filename": "q3-report.pdf"
            }
          }
        ]
      }
    ]
  }
  EOF
  ```
</CodeGroup>

## 文件 URL

如果文件已托管在公开的 HTTP 或 HTTPS URL 上，请在 `file_data` 中传递 URL，而非 base64 编码：

```json theme={"dark"}
{
  "model": "openai-gpt-55",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Identify the governing law, renewal terms, and termination rights in this agreement."
        },
        {
          "type": "file",
          "file": {
            "file_data": "https://example.com/contracts/vendor-agreement.pdf",
            "filename": "vendor-agreement.pdf"
          }
        }
      ]
    }
  ]
}
```

<Warning>
  仅使用 Venice 可在无需身份验证的情况下获取的公开 URL。对于私有文件，请发送 base64 data URL。
</Warning>

## 多个文件

您可以在同一消息中包含多个文件块。在文件前放置简短的文本指令，让模型知道如何使用它们。

```json theme={"dark"}
{
  "model": "openai-gpt-55",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Compare these two policy drafts. Return the material differences and recommend which version is clearer."
        },
        {
          "type": "file",
          "file": {
            "file_data": "data:application/pdf;base64,JVBERi0xLjQK...",
            "filename": "policy-v1.pdf"
          }
        },
        {
          "type": "file",
          "file": {
            "file_data": "data:application/pdf;base64,JVBERi0xLjQK...",
            "filename": "policy-v2.pdf"
          }
        }
      ]
    }
  ]
}
```

为获得最佳效果，请清晰地命名每个文件并在 prompt 中引用这些名称。

## Data URL

对于本地文件，将文件字节编码为 base64 并加上正确的 MIME 类型前缀：

| 文件类型     | Data URL 前缀                                                                              |
| -------- | ---------------------------------------------------------------------------------------- |
| PDF      | `data:application/pdf;base64,`                                                           |
| DOCX     | `data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,`   |
| PPTX     | `data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64,` |
| XLSX     | `data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,`         |
| CSV      | `data:text/csv;base64,`                                                                  |
| Markdown | `data:text/markdown;base64,`                                                             |
| 纯文本      | `data:text/plain;base64,`                                                                |
| JSON     | `data:application/json;base64,`                                                          |

如果您不知道确切的 MIME 类型，请使用 `application/octet-stream`。包含准确的 `filename` 仍可帮助 Venice 识别和显示文件。

## 处理大文件

由于文件会变成 prompt 文本，大文件会增加延迟、token 用量和成本。请注意模型的上下文窗口。

原始文件必须不超过 25MB。Base64 编码会使请求大小增加约 33%，因此接近 25MB 限制的文件将产生更大的 JSON 请求体。

处理大文件的良好模式：

* 询问特定任务，而不是宽泛的"分析一切"。
* 仅包含当前回答所需的文档。
* 对于长报告或代码库，使用更大 `availableContextTokens` 的模型。
* 如果您同时使用 [prompt 缓存](/guides/features/prompt-caching)，请将稳定的、重复的文档放在动态用户问题之前。
* 当您预期长响应时使用 `stream: true`。

## 文件输入 vs. 文本解析器

当您希望模型立即对文件进行推理时，使用聊天文件输入。

当您希望先提取文本、检查 token 计数、将提取的文本存储在自己的系统中或将相同提取的文本发送到多个请求时，使用[文本解析器 API](/api-reference/endpoint/augment/text-parser)。

| 需求                       | 使用                          |
| ------------------------ | --------------------------- |
| 在一个请求中向模型询问文档            | 聊天文件输入                      |
| 在不进行模型推理的情况下提取文本         | 文本解析器 API                   |
| 在 prompt 之前检查提取的 token 数 | 文本解析器 API                   |
| 在多个请求中重用提取的文本            | 文本解析器 API，然后将文本包含在 prompt 中 |

## 最佳实践

* 尽可能包含 `filename`，尤其是在发送多个文件时。
* 将指令放在文件块之前，使模型在读取提取的内容之前了解任务。
* 仅对可在无 cookie、请求头或签名会话状态的情况下获取的文件使用公开 URL。
* 对于私有文件或在您应用内生成的文件，优先使用 base64 data URL。
* 提出聚焦的问题，并指定您想要的输出格式。
* 对于结构化提取，将文件输入与[结构化响应](/guides/features/structured-responses)结合使用。

## 故障排查

<AccordionGroup>
  <Accordion title="模型表示无法访问文件">
    确保消息 content 使用数组并包含一个 `type: "file"` 块。如果您使用了 URL，请验证它在无需身份验证的情况下公开可访问。
  </Accordion>

  <Accordion title="请求很慢或费用高">
    该文件可能提取出大量文本。使用更大上下文的模型、缩小任务范围、发送更少文件，或使用文本解析器 API 预先提取并裁剪文本。
  </Accordion>

  <Accordion title="响应忽略了我的某个文件">
    给每个文件一个描述性的 `filename`，并在 prompt 中直接引用文件名。例如，"Compare `policy-v1.pdf` against `policy-v2.pdf`."
  </Accordion>

  <Accordion title="模型拒绝了文件内容">
    文件输入在兼容的聊天模型上可用。请查看[模型页面](/models/overview)了解当前模型功能和上下文限制，或尝试当前的大上下文文本模型。
  </Accordion>
</AccordionGroup>
