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

# 上传带有追踪的文件

当您使用 [`@traceable` 装饰器或 `traceable` 包装器](/langsmith/annotate-code#use-%40traceable-%2F-traceable) 进行追踪时，LangSmith 支持在追踪数据旁上传二进制文件（如图像、音频、视频、PDF 和 CSV）。当使用具有多模态输入或输出的 LLM 流水线时，这尤其有用。

在 [Python](#python) 和 [TypeScript](#typescript) SDK 中，您可以通过指定每个文件的 MIME 类型和二进制内容来为追踪添加附件。本页说明如何在 Python 中使用 `Attachment` 类型以及在 TypeScript 中使用 `Uint8Array` / `ArrayBuffer` 来定义和追踪附件。

## Python

在 [Python SDK](/langsmith/smith-python-sdk) 中，您可以使用 `Attachment` 类型向追踪添加文件。每个 `Attachment` 需要：

* `mime_type` (str)：文件的 MIME 类型（例如 `"image/png"`）。
* `data` (bytes | Path)：文件的二进制内容，或文件路径。

为了方便，您也可以使用 `(mime_type, data)` 形式的元组来定义附件。

有两种方式提供文件数据：

* 自己加载字节并直接传递（适用于所有环境），或者
* 传递一个 `Path` 对象，并通过在 `@traceable` 装饰器上设置 `dangerously_allow_filesystem=True` 让 SDK 读取文件。

  <Note>
    `dangerously_allow_filesystem` 标志是为服务器和多租户环境设置的安全防护，在这些环境中，用户控制的输入可能影响文件路径。在受信任的环境（本地脚本或您拥有文件路径的受控流水线）中，启用它是安全的。
  </Note>

使用 `@traceable` 装饰一个函数，并将您的 `Attachment` 实例作为参数包含在内。以下示例演示了两种方法：将文件字节手动加载到 `Attachment` 中，以及传递一个 `Path` 对象并设置 `dangerously_allow_filesystem=True`：

```python Python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langsmith import traceable
from langsmith.schemas import Attachment
from pathlib import Path
import os

# 如果要使用文件路径，必须将 dangerously_allow_filesystem 设置为 True
@traceable(dangerously_allow_filesystem=True)
def trace_with_attachments(
    val: int,
    text: str,
    image: Attachment,
    audio: Attachment,
    video: Attachment,
    pdf: Attachment,
    csv: Attachment,
):
    return f"Processed: {val}, {text}, {len(image.data)}, {len(audio.data)}, {len(video.data)}, {len(pdf.data), {len(csv.data)}}"

# 将文件加载为字节的辅助函数
def load_file(file_path: str) -> bytes:
    with open(file_path, "rb") as f:
        return f.read()

# 加载文件并创建附件
image_data = load_file("my_image.png")
audio_data = load_file("my_mp3.mp3")
video_data = load_file("my_video.mp4")
pdf_data = load_file("my_document.pdf")

image_attachment = Attachment(mime_type="image/png", data=image_data)
audio_attachment = Attachment(mime_type="audio/mpeg", data=audio_data)
video_attachment = Attachment(mime_type="video/mp4", data=video_data)
pdf_attachment = ("application/pdf", pdf_data) # 可以直接定义为 (mime_type, data) 的元组
csv_attachment = Attachment(mime_type="text/csv", data=Path(os.getcwd()) / "my_csv.csv")

# 定义其他参数
val = 42
text = "Hello, world!"

# 使用带追踪的附件调用函数
result = trace_with_attachments(
    val=val,
    text=text,
    image=image_attachment,
    audio=audio_attachment,
    video=video_attachment,
    pdf=pdf_attachment,
    csv=csv_attachment,
)
```

## TypeScript

在 [TypeScript SDK](/langsmith/smith-js-ts-sdk) 中，您可以使用 `Uint8Array` 或 `ArrayBuffer` 作为数据类型来为追踪添加附件。每个附件的 MIME 类型在 `extractAttachments` 中指定：

* `Uint8Array`：适用于直接处理二进制数据。
* `ArrayBuffer`：表示固定长度的二进制数据，您可以根据需要将其转换为 `Uint8Array`。

在 TypeScript SDK 中，`extractAttachments` 函数是 `traceable` 配置中的一个可选参数。当被 `traceable` 包装的函数被调用时，它会从您的输入中提取二进制数据（例如图像、音频文件），并将其与其他追踪数据一起记录，同时指定它们的 MIME 类型。

<Note>
  在 TypeScript SDK 中，您不能直接传递文件路径，因为在所有运行时环境中并不支持访问本地文件。
</Note>

使用 `traceable` 包装您的函数，并在 `extractAttachments` 选项中包含您的附件。其签名是：

```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
type AttachmentData = Uint8Array | ArrayBuffer;
type Attachments = Record<string, [string, AttachmentData]>;

extractAttachments?: (
    ...args: Parameters<Func>
) => [Attachments | undefined, KVMap];
```

以下示例展示了一个完整的实现：

```typescript TypeScript theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import { traceable } from "langsmith/traceable";

const traceableWithAttachments = traceable(
    (
        val: number,
        text: string,
        attachment: Uint8Array,
        attachment2: ArrayBuffer,
        attachment3: Uint8Array,
        attachment4: ArrayBuffer,
        attachment5: Uint8Array,
    ) =>
        `Processed: ${val}, ${text}, ${attachment.length}, ${attachment2.byteLength}, ${attachment3.length}, ${attachment4.byteLength}, ${attachment5.byteLength}`,
    {
        name: "traceWithAttachments",
        extractAttachments: (
            val: number,
            text: string,
            attachment: Uint8Array,
            attachment2: ArrayBuffer,
            attachment3: Uint8Array,
            attachment4: ArrayBuffer,
            attachment5: Uint8Array,
        ) => [
            {
                "image inputs": ["image/png", attachment],
                "mp3 inputs": ["audio/mpeg", new Uint8Array(attachment2)],
                "video inputs": ["video/mp4", attachment3],
                "pdf inputs": ["application/pdf", new Uint8Array(attachment4)],
                "csv inputs": ["text/csv", new Uint8Array(attachment5)],
            },
            { val, text },
        ],
    }
);

const fs = Deno // 或 Node.js fs 模块
const image = await fs.readFile("my_image.png"); // Uint8Array
const mp3Buffer = await fs.readFile("my_mp3.mp3");
const mp3ArrayBuffer = mp3Buffer.buffer; // 转换为 ArrayBuffer
const video = await fs.readFile("my_video.mp4"); // Uint8Array
const pdfBuffer = await fs.readFile("my_document.pdf");
const pdfArrayBuffer = pdfBuffer.buffer; // 转换为 ArrayBuffer
const csv = await fs.readFile("test-vals.csv"); // Uint8Array

// 定义示例参数
const val = 42;
const text = "Hello, world!";

// 使用文件调用 traceableWithAttachments
const result = await traceableWithAttachments(
    val, text, image, mp3ArrayBuffer, video, pdfArrayBuffer, csv
);
```

## 相关内容

* [管理数据集](/langsmith/manage-datasets)
* [设置 LLM 作为评判的在线评估器](/langsmith/online-evaluations-llm-as-judge)

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs)通过 MCP 连接到 Claude、VSCode 等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/langsmith/upload-files-with-traces.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
