0

Add fragment to conversation

by
Published Aug 26, 2024
Script dust Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 652 days ago
1
type Dust = {
2
	apiKey: string
3
	workspaceId: string
4
}
5

6
export async function main(
7
	resource: Dust,
8
	conversationId: string,
9
	body: {
10
		title: string
11
		content: string | Buffer
12
		url: string | null
13
		contentType:
14
			| 'text/plain'
15
			| 'text/csv'
16
			| 'text/tsv'
17
			| 'text/comma-separated-values'
18
			| 'text/tab-separated-values'
19
			| 'text/markdown'
20
			| 'application/pdf'
21
			| 'file_attachment'
22
			| 'image/jpeg'
23
			| 'image/png'
24
		context: {
25
			username: string
26
			timezone: string
27
			fullName: string | null
28
			email: string | null
29
			profilePictureUrl: string | null
30
			origin?: 'slack' | 'web' | 'api'
31
		} | null
32
	}
33
) {
34
	const endpoint = `https://dust.tt/api/v1/w/${resource.workspaceId}/assistant/conversations/${conversationId}/content_fragments`
35

36
	let content: string
37

38
	// Convert Buffer to base64 string for binary content types
39
	if (body.content instanceof Buffer) {
40
		content = body.content.toString('base64')
41
	} else {
42
		content = body.content
43
	}
44

45
	const requestBody = {
46
		...body,
47
		content
48
	}
49

50
	const response = await fetch(endpoint, {
51
		method: 'POST',
52
		headers: {
53
			'Content-Type': 'application/json',
54
			Authorization: `Bearer ${resource.apiKey}`
55
		},
56
		body: JSON.stringify(requestBody)
57
	})
58

59
	if (!response.ok) {
60
		throw new Error(`HTTP error! status: ${response.status}`)
61
	}
62

63
	const data = await response.json()
64
	return data.contentFragment
65
}
66