forked from openai/openai-assistants-quickstart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.tsx
77 lines (66 loc) · 2.43 KB
/
route.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import { assistantId } from "@/app/assistant-config";
import { openai } from "@/app/openai";
// upload file to assistant's vector store
export async function POST(request) {
const formData = await request.formData(); // process file as FormData
const file = formData.get("file"); // retrieve the single file from FormData
const vectorStoreId = await getOrCreateVectorStore(); // get or create vector store
// upload using the file stream
const openaiFile = await openai.files.create({
file: file,
purpose: "assistants",
});
// add file to vector store
await openai.beta.vectorStores.files.create(vectorStoreId, {
file_id: openaiFile.id,
});
return new Response();
}
// list files in assistant's vector store
export async function GET() {
const vectorStoreId = await getOrCreateVectorStore(); // get or create vector store
const fileList = await openai.beta.vectorStores.files.list(vectorStoreId);
const filesArray = await Promise.all(
fileList.data.map(async (file) => {
const fileDetails = await openai.files.retrieve(file.id);
const vectorFileDetails = await openai.beta.vectorStores.files.retrieve(
vectorStoreId,
file.id
);
return {
file_id: file.id,
filename: fileDetails.filename,
status: vectorFileDetails.status,
};
})
);
return Response.json(filesArray);
}
// delete file from assistant's vector store
export async function DELETE(request) {
const body = await request.json();
const fileId = body.fileId;
const vectorStoreId = await getOrCreateVectorStore(); // get or create vector store
await openai.beta.vectorStores.files.del(vectorStoreId, fileId); // delete file from vector store
return new Response();
}
/* Helper functions */
const getOrCreateVectorStore = async () => {
const assistant = await openai.beta.assistants.retrieve(assistantId);
// if the assistant already has a vector store, return it
if (assistant.tool_resources?.file_search?.vector_store_ids?.length > 0) {
return assistant.tool_resources.file_search.vector_store_ids[0];
}
// otherwise, create a new vector store and attatch it to the assistant
const vectorStore = await openai.beta.vectorStores.create({
name: "sample-assistant-vector-store",
});
await openai.beta.assistants.update(assistantId, {
tool_resources: {
file_search: {
vector_store_ids: [vectorStore.id],
},
},
});
return vectorStore.id;
};