1 | import { removeObjectEmptyFields } from "https://deno.land/x/windmill_helpers@v1.1.1/mod.ts"; |
2 | import { |
3 | Configuration, |
4 | CreateCompletionRequest, |
5 | OpenAIApi, |
6 | } from "npm:openai@3.2.1"; |
7 |
|
8 |
|
9 | * You can read about the parameters at |
10 | * https://platform.openai.com/docs/api-reference/completions/create |
11 | * |
12 | * @returns An object with the **lowercase** values of the `translate_to` array as keys. |
13 | * |
14 | * *For example:* |
15 | * ``` |
16 | * { french: "J'aime les pommes", german: "Ich liebe Äpfel" } |
17 | * ``` |
18 | */ |
19 | type Openai = { |
20 | api_key: string; |
21 | organization_id: string; |
22 | }; |
23 | export async function main( |
24 | auth: Openai, |
25 | text: string, |
26 | translate_to: string[] = ["french", "german"], |
27 | model: string = "text-davinci-003", |
28 | max_tokens: number = 100, |
29 | ) { |
30 | const configuration = new Configuration({ |
31 | apiKey: auth.api_key, |
32 | organization: auth.organization_id, |
33 | }); |
34 | const openai = new OpenAIApi(configuration); |
35 |
|
36 | const prompt = `Translate the text below into the languages found in this array: |
37 | [${translate_to.map((l) => l.trim().toLowerCase()).join(", ")}] |
38 | Apply the following rules: |
39 | - return ONLY a valid JSON object |
40 | - the object keys are strictly the languages in the array above |
41 | - the values are the corresponding translations |
42 | - do NOT try to complete the original text |
43 |
|
44 | ${text}`; |
45 | console.log(prompt); |
46 | const request = removeObjectEmptyFields({ |
47 | model, |
48 | prompt, |
49 | max_tokens, |
50 | temperature: 0.3, |
51 | top_p: 1.0, |
52 | frequency_penalty: 0.0, |
53 | presence_penalty: 0.0, |
54 | }) as CreateCompletionRequest; |
55 | const { data } = await openai.createCompletion(request); |
56 | console.log(data?.choices[0]?.text); |
57 |
|
58 | return JSON.parse(data?.choices[0]?.text.replaceAll('"', '"') ?? ""); |
59 | } |
60 |
|