0

Upload a file to the corpus

by
Published Nov 5, 2024

Upload files such as PDFs and Word Documents.

Script vectara Verified

The script

Submitted by hugo697 Bun
Verified 581 days ago
1
//native
2
type Vectara = {
3
	apiKey: string
4
}
5
/**
6
 * Upload a file to the corpus
7
 * Upload files such as PDFs and Word Documents.
8
 */
9
export async function main(
10
	auth: Vectara,
11
	corpus_key: string,
12
	body: {
13
		metadata?: {}
14
		filename?: string
15
		file: {
16
			base64: string
17
			type:
18
				| 'image/png'
19
				| 'image/jpeg'
20
				| 'image/gif'
21
				| 'application/pdf'
22
				| 'appication/json'
23
				| 'text/csv'
24
				| 'text/plain'
25
				| 'audio/mpeg'
26
				| 'audio/wav'
27
				| 'video/mp4'
28
			name: string
29
		}
30
	}
31
) {
32
	const url = new URL(`https://api.vectara.io/v2/corpora/${corpus_key}/upload_file`)
33

34
	const formData = new FormData()
35
	for (const [k, v] of Object.entries(body)) {
36
		if (v !== undefined && v !== '') {
37
			if (['file'].includes(k)) {
38
				const { base64, type, name } = v as {
39
					base64: string
40
					type: string
41
					name: string
42
				}
43
				formData.append(
44
					k,
45
					new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
46
						type
47
					}),
48
					name
49
				)
50
			} else {
51
				formData.append(k, String(v))
52
			}
53
		}
54
	}
55
	const response = await fetch(url, {
56
		method: 'POST',
57
		headers: {
58
			'x-api-key': auth.apiKey
59
		},
60
		body: formData
61
	})
62
	if (!response.ok) {
63
		const text = await response.text()
64
		throw new Error(`${response.status} ${text}`)
65
	}
66
	return await response.json()
67
}
68