Create Translation ( openai)
One script reply has been approved by the moderators Verified

Created by adam186 38 days ago Viewed 5 times 1 Point

Translate given text to many different languages.

No comments yet

Login to be able to comment
Points: 0
deno
One script reply has been approved by the moderators
Ap­pro­ved
import type { Resource } from "https://deno.land/x/windmill@v1.89.0/mod.ts";
import { removeObjectEmptyFields } from "https://deno.land/x/windmill_helpers@v1.1.1/mod.ts";
import {
  Configuration,
  CreateCompletionRequest,
  OpenAIApi,
} from "npm:openai@3.2.1";

/**
 * You can read about the parameters at
 * https://platform.openai.com/docs/api-reference/completions/create
 *
 * @returns An object with the **lowercase** values of the `translate_to` array as keys.
 *
 * *For example:*
 * ```
 *  { french: "J'aime les pommes", german: "Ich liebe Äpfel" }
 * ```
 */
export async function main(
  auth: Resource<"openai">,
  text: string,
  translate_to: string[] = ["french", "german"],
  model: string = "text-davinci-003",
  max_tokens: number = 100,
) {
  const configuration = new Configuration({
    apiKey: auth.api_key,
    organization: auth.organization_id,
  });
  const openai = new OpenAIApi(configuration);

  const prompt =
    `Translate the text below into the languages found in this array:
[${translate_to.map((l) => l.trim().toLowerCase()).join(", ")}]
Apply the following rules:
  - return ONLY a valid JSON object
  - the object keys are strictly the languages in the array above
  - the values are the corresponding translations
  - do NOT try to complete the original text

${text}`;
  console.log(prompt);
  const request = removeObjectEmptyFields({
    model,
    prompt,
    max_tokens,
    temperature: 0.3,
    top_p: 1.0,
    frequency_penalty: 0.0,
    presence_penalty: 0.0,
  }) as CreateCompletionRequest;
  const { data } = await openai.createCompletion(request);
  console.log(data?.choices[0]?.text);

  return JSON.parse(data?.choices[0]?.text.replaceAll('"', '"') ?? "");
}

Submitted by adam186 38 days ago

Edited 38 days ago

No comments yet

Login to be able to comment