0
Create file
One script reply has been approved by the moderators Verified

Upload a file that can be used across various endpoints. The size of all the files uploaded by one organization can be up to 100 GB.

The size of individual files can be a maximum of 512 MB or 2 million tokens for Assistants. See the Assistants Tools guide to learn more about the types of files supported. The Fine-tuning API only supports .jsonl files.

Please contact us if you need to increase these storage limits.

Created by hugo697 357 days ago Viewed 9003 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 357 days ago
1
type Openai = {
2
  api_key: string;
3
  organization_id: string;
4
};
5
type Base64 = string;
6
/**
7
 * Create file
8
 * Upload a file that can be used across various endpoints. The size of all the files uploaded by one organization can be up to 100 GB.
9

10
The size of individual files can be a maximum of 512 MB or 2 million tokens for Assistants. See the Assistants Tools guide to learn more about the types of files supported. The Fine-tuning API only supports `.jsonl` files.
11

12
Please [contact us](https://help.openai.com/) if you need to increase these storage limits.
13

14
 */
15
export async function main(
16
  auth: Openai,
17
  body: {
18
    file: {
19
      base64: Base64;
20
      type:
21
        | "image/png"
22
        | "image/jpeg"
23
        | "image/gif"
24
        | "application/pdf"
25
        | "appication/json"
26
        | "text/csv"
27
        | "text/plain"
28
        | "audio/mpeg"
29
        | "audio/wav"
30
        | "video/mp4";
31
      name: string;
32
    };
33
    purpose: "fine-tune" | "assistants";
34
  }
35
) {
36
  const url = new URL(`https://api.openai.com/v1/files`);
37

38
  const formData = new FormData();
39
  for (const [k, v] of Object.entries(body)) {
40
    if (v !== undefined && v !== "") {
41
      if (["file"].includes(k)) {
42
        const { base64, type, name } = v as {
43
          base64: Base64;
44
          type: string;
45
          name: string;
46
        };
47
        formData.append(
48
          k,
49
          new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
50
            type,
51
          }),
52
          name
53
        );
54
      } else {
55
        formData.append(k, String(v));
56
      }
57
    }
58
  }
59
  const response = await fetch(url, {
60
    method: "POST",
61
    headers: {
62
      "OpenAI-Organization": auth.organization_id,
63
      Authorization: "Bearer " + auth.api_key,
64
    },
65
    body: formData,
66
  });
67
  if (!response.ok) {
68
    const text = await response.text();
69
    throw new Error(`${response.status} ${text}`);
70
  }
71
  return await response.json();
72
}
73