|
| 1 | +import { AppContext } from "../mod.ts"; |
| 2 | + |
| 3 | +export interface Props { |
| 4 | + /** |
| 5 | + * @description The URL of the file to upload |
| 6 | + */ |
| 7 | + fileUrl?: string; |
| 8 | + |
| 9 | + /** |
| 10 | + * @description The content of the file to upload (text only) |
| 11 | + */ |
| 12 | + fileContent?: string; |
| 13 | + |
| 14 | + /** |
| 15 | + * @description The optional name of the file with extension (if not provided, the file will be named "file-${timestamp}.txt") |
| 16 | + */ |
| 17 | + fileName?: string; |
| 18 | + |
| 19 | + /** |
| 20 | + * @description The optional metadata to attach to the file |
| 21 | + */ |
| 22 | + metadata?: string; |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * @title Upload File |
| 27 | + * @name Upload File |
| 28 | + * @description Uploads a file to the assistant |
| 29 | + */ |
| 30 | +const action = async ( |
| 31 | + props: Props, |
| 32 | + _req: Request, |
| 33 | + ctx: AppContext, |
| 34 | +) => { |
| 35 | + if (!props.fileUrl && !props.fileContent) { |
| 36 | + return { |
| 37 | + success: false, |
| 38 | + error: "No file URL or content provided", |
| 39 | + }; |
| 40 | + } |
| 41 | + |
| 42 | + let fileBuffer: ArrayBuffer | null = null; |
| 43 | + let contentType: string | null = null; |
| 44 | + |
| 45 | + if (props.fileUrl) { |
| 46 | + const fileResponse = await fetch(props.fileUrl); |
| 47 | + contentType = fileResponse.headers.get("content-type"); |
| 48 | + fileBuffer = await fileResponse.arrayBuffer(); |
| 49 | + } |
| 50 | + |
| 51 | + if (props.fileContent) { |
| 52 | + fileBuffer = new TextEncoder().encode(props.fileContent) |
| 53 | + .buffer as ArrayBuffer; |
| 54 | + contentType = "text/plain"; |
| 55 | + } |
| 56 | + |
| 57 | + if (!fileBuffer) { |
| 58 | + return { |
| 59 | + success: false, |
| 60 | + error: |
| 61 | + "Could not create a file buffer from the provided file URL or content", |
| 62 | + }; |
| 63 | + } |
| 64 | + |
| 65 | + const file = new File( |
| 66 | + [fileBuffer], |
| 67 | + props.fileName || `file-${Date.now()}.txt`, |
| 68 | + { type: contentType || "application/octet-stream" }, |
| 69 | + ); |
| 70 | + |
| 71 | + const formData = new FormData(); |
| 72 | + formData.append("file", file); |
| 73 | + |
| 74 | + const response = await ctx.client |
| 75 | + ["POST /assistant/files/:assistant_name"]({ |
| 76 | + assistant_name: ctx.assistant, |
| 77 | + metadata: props.metadata, |
| 78 | + }, { |
| 79 | + body: formData, |
| 80 | + }); |
| 81 | + |
| 82 | + const result = await response.json(); |
| 83 | + console.log({ result }); |
| 84 | + |
| 85 | + if (result.error_message) { |
| 86 | + return { |
| 87 | + success: false, |
| 88 | + error: result.error_message, |
| 89 | + }; |
| 90 | + } |
| 91 | + |
| 92 | + return { |
| 93 | + success: true, |
| 94 | + file: result, |
| 95 | + }; |
| 96 | +}; |
| 97 | + |
| 98 | +export default action; |
0 commit comments