Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance external image hosting in agent configuration #4565

Merged
merged 6 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ export function AvatarPicker({
style={{ display: "none" }}
onChange={onFileChange}
ref={fileInputRef}
accept=".png,.jpg,.jpeg"
/>

<div className="h-full w-full overflow-visible">
Expand Down
22 changes: 22 additions & 0 deletions front/lib/api/assistant/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { agentConfigurationWasUpdatedBy } from "@app/lib/api/assistant/recent_au
import { agentUserListStatus } from "@app/lib/api/assistant/user_relation";
import { compareAgentsForSort } from "@app/lib/assistant";
import type { Authenticator } from "@app/lib/auth";
import { getFileContentType } from "@app/lib/dfs";
import {
AgentConfiguration,
AgentDataSourceConfiguration,
Expand Down Expand Up @@ -754,6 +755,20 @@ export async function getAgentNames(auth: Authenticator): Promise<string[]> {
return agents.map((a) => a.name);
}

async function isSelfHostedImageWithValidContentType(pictureUrl: string) {
const filename = pictureUrl.split("/").at(-1);
if (!filename) {
return false;
}

const contentType = await getFileContentType("PUBLIC_UPLOAD", filename);
if (!contentType) {
return false;
}

return contentType.includes("image");
}

/**
* Create Agent Configuration
*/
Expand Down Expand Up @@ -789,6 +804,13 @@ export async function createAgentConfiguration(
throw new Error("Unexpected `auth` without `user`.");
}

const isValidPictureUrl = await isSelfHostedImageWithValidContentType(
pictureUrl
);
if (!isValidPictureUrl) {
return new Err(new Error("Invalid picture url."));
}

let version = 0;
let listStatusOverride: AgentUserListStatus | null = null;

Expand Down
12 changes: 12 additions & 0 deletions front/lib/dfs/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { EnvironmentConfig } from "@dust-tt/types";

const config = {
getServiceAccount: (): string => {
return EnvironmentConfig.getEnvVariable("SERVICE_ACCOUNT");
},
getPublicUploadBucket: (): string => {
return EnvironmentConfig.getEnvVariable("DUST_UPLOAD_BUCKET");
},
};

export default config;
52 changes: 52 additions & 0 deletions front/lib/dfs/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import type { Bucket } from "@google-cloud/storage";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gcs rather than dfs in name no?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I stick with DFS for this file/class but all other occurrences will go with GCS.

import { Storage } from "@google-cloud/storage";
import type formidable from "formidable";
import fs from "fs";

import config from "@app/lib/dfs/config";

type SupportedBucketKeyType = "PUBLIC_UPLOAD";

const storage = new Storage({
keyFilename: config.getServiceAccount(),
});

const bucketKeysToBucket: Record<SupportedBucketKeyType, Bucket> = {
PUBLIC_UPLOAD: storage.bucket(config.getPublicUploadBucket()),
};

export async function uploadToBucket(
bucketKey: SupportedBucketKeyType,
file: formidable.File
) {
const bucket = bucketKeysToBucket[bucketKey];

const gcsFile = bucket.file(file.newFilename);
const fileStream = fs.createReadStream(file.filepath);

return new Promise((resolve, reject) =>
fileStream
.pipe(
gcsFile.createWriteStream({
metadata: {
contentType: file.mimetype,
},
})
)
.on("error", reject)
.on("finish", () => resolve(gcsFile))
);
}

export async function getFileContentType(
bucketKey: SupportedBucketKeyType,
filename: string
): Promise<string | null> {
const bucket = bucketKeysToBucket[bucketKey];

const gcsFile = bucket.file(filename);

const [metadata] = await gcsFile.getMetadata();

return metadata.contentType;
}
46 changes: 18 additions & 28 deletions front/pages/api/w/[wId]/assistant/agent_configurations/avatar.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { Storage } from "@google-cloud/storage";
import { IncomingForm } from "formidable";
import fs from "fs";
import type { NextApiRequest, NextApiResponse } from "next";

import { uploadToBucket } from "@app/lib/dfs";
import { withLogging } from "@app/logger/withlogging";

const { DUST_UPLOAD_BUCKET = "", SERVICE_ACCOUNT } = process.env;
const { DUST_UPLOAD_BUCKET = "" } = process.env;

export const config = {
api: {
Expand All @@ -19,39 +18,30 @@ async function handler(
): Promise<void> {
if (req.method === "POST") {
try {
const form = new IncomingForm();
const [_fields, files] = await form.parse(req);
void _fields;
const form = new IncomingForm({
filter: ({ mimetype }) => {
if (!mimetype) {
return false;
}

// Only allow uploading image.
return mimetype.includes("image");
},
maxFileSize: 3 * 1024 * 1024, // 3 mb.
});

const [, files] = await form.parse(req);

const maybeFiles = files.file;
const { file: maybeFiles } = files;

if (!maybeFiles) {
res.status(400).send("No file uploaded.");
return;
}

const file = maybeFiles[0];

const storage = new Storage({
keyFilename: SERVICE_ACCOUNT,
});

const bucket = storage.bucket(DUST_UPLOAD_BUCKET);
const gcsFile = await bucket.file(file.newFilename);
const fileStream = fs.createReadStream(file.filepath);
const [file] = maybeFiles;

await new Promise((resolve, reject) =>
fileStream
.pipe(
gcsFile.createWriteStream({
metadata: {
contentType: file.mimetype,
},
})
)
.on("error", reject)
.on("finish", resolve)
);
await uploadToBucket("PUBLIC_UPLOAD", file);

const fileUrl = `https://storage.googleapis.com/${DUST_UPLOAD_BUCKET}/${file.newFilename}`;

Expand Down
Loading