如何检索OpenAI映像并将其保存到S3 bucket



我想在OpenAI/Dall E中生成一个图像,并将其保存到S3 Bucket。

到目前为止,我可以获得图像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 buffer
export 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);
}
}

最新更新