我想获取在OpenAI/Dall E生成的图像并将其保存到S3存储桶中。
到目前为止,我可以获取图像URL并创建一个缓冲区,如下所示:
const configuration = new Configuration({ apiKey: procEnvVars.OPENAI_API_KEY,});export const openai = new OpenAIApi(configuration);const defaultImageParams: CreateImageRequest = { n: 1, prompt: "a bad request message",};interface InputParams extends CreateImageRequest { prompt: string; // make this mandatory for the function params}// Once we get a URL from the OpenAI API, we want to convert it to a bufferexport async function getBufferFromUrl(openAiUrl: string) { const axiosResponse = await axios({ url: openAiUrl, //your url method: "GET", responseType: "arraybuffer", }); const data = axiosResponse.data; if (!(data instanceof Buffer)) throw new Error("Axios response should be of type Buffer"); return data;}export async function getUrlFromOpenAi(inputParams: InputParams) { const ImageResponse = await openai.createImage({ ...defaultImageParams, ...inputParams, }); const dataArray = ImageResponse.data.data; if (!dataArray || dataArray.length === 0) { console.error({ error: "We did not return choices from createOpenAiImage()", data: ImageResponse.data, datadata: ImageResponse.data.data, }); } return dataArray;}
回答:
接下来,我们需要将缓冲区保存到S3中:
// Create service client module using ES6 syntax.import { S3Client } from "@aws-sdk/client-s3";// Set the AWS Region.const REGION = "eu-west-2";// Create an Amazon S3 service client object.const s3Client = new S3Client({ region: REGION });export { s3Client };// Import required AWS SDK clients and commands for Node.js.import { PutObjectCommand } from "@aws-sdk/client-s3";// Set the parameters.export const bucketParams = { Bucket: "<my s3 bucket name. Can be found in S3 console>",};// Create and upload an object to the S3 bucket.export async function putS3Object(inputParams: { Body: Buffer; Key: string }) { try { const data = await s3Client.send( new PutObjectCommand({ ...bucketParams, Body: inputParams.Body, Key: `public/myFolder/${inputParams.Key}`, }) ); console.log( "Successfully uploaded object: " + bucketParams.Bucket + "/" + `public/myFolder/${inputParams.Key}` ); return data; // For unit tests. } catch (err) { console.log("Error", err); }}