6
7/**
8 * OpenAI text completion. https://platform.openai.com/docs/api-reference/completions
9 *
10 * val.town has generously provided a free daily quota. Until the quota is met, no need to provide an API key.
11 * To see if the quota has been met, you can run @patrickjm.openAiFreeQuotaExceeded()
12 *
13 * For full REST API access, see @patrickjm.openAiTextCompletion
14 */
15export let gpt3 = async (params: {
20 const MODEL = "text-davinci-003";
21
22 // Determine whether to use provided apiKey or free usage apiKey based on daily quota.
23 const apiKey = params.openAiKey ?? openAiFreeUsageConfig.key;
24 const exceeded = await openAiFreeQuotaExceeded();
25 if (!params.openAiKey && exceeded) {
27 }
28
29 // If using free token, first check inputs against moderation api
30 if (!params.openAiKey) {
31 const moderation = await openAiModeration({
32 apiKey,
33 input: params.prompt,
34 });
35 if (moderation.results.some((r) => r.flagged)) {
36 throw new Error(
37 "Sorry, this prompt was flagged by OpenAI moderation. If you provide your own API key, moderation will be turned off."
38 );
39 }
40 }
41
42 // Call completion API
43 const response = await openAiTextCompletion({
44 apiKey: apiKey,
45 prompt: params.prompt,
46 model: MODEL,