1 回答
- 最新
- 投票最多
- 评论最多
0
【以下的回答经过翻译处理】 我找到了答案...
如果对任何人有帮助,下面的代码在顺序中混合了同步和异步函数调用,在等待异步函数完成后继续到下一个函数。
const { Configuration, OpenAIApi } = require("openai");
exports.handler = async function(event, context, callback) {
var output;
try {
const rule1 = getStart(); // call the first (sync) function
const rule2 = await getMiddle(event.prompt).then(res => { // call the second (async) function and wait
return res.data.choices[0].text;
}).catch(error => {
return error.message;
});
output = getEnd(rule1 + ' ' + rule2); // call the third (sync) function
console.log('result: ' + output);
}
catch (e){
output = e.message;
}
let response = {
statusCode: 200,
headers: { "Content-type" : "application/json" },
body: JSON.stringify(output)
};
return response;
};
function getStart()
{
return '<sentence>Hi there,';
}
async function getMiddle(prompt)
{
console.log("getMiddle('" + prompt + "')");
const configuration = new Configuration({
apiKey: "my-api-key-here",
});
const openai = new OpenAIApi(configuration);
return openai.createCompletion({
model: "text-davinci-003",
prompt: prompt,
temperature: 0.7,
max_tokens: 500,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
});
}
function getEnd(resp)
{
return resp + '</sentence>';
}
Response
{
"statusCode": 200,
"headers": {
"Content-type": "application/json"
},
"body": "\"<sentence>Hi there, \\n\\nThe fox usually makes a sound similar to \\\"Skrr! Skrr!\\\"</sentence>\""
}
Function Logs
START RequestId: 41cc46f8-9a9b-4500-854e-574739511e2e Version: $LATEST
2023-04-27T10:55:22.820Z 41cc46f8-9a9b-4500-854e-574739511e2e INFO getMiddle('what did the fox say?')
2023-04-27T10:55:25.040Z 41cc46f8-9a9b-4500-854e-574739511e2e INFO result: <sentence>Hi there,
The fox usually makes a sound similar to "Skrr! Skrr!"</sentence>
END RequestId: 41cc46f8-9a9b-4500-854e-574739511e2e