summaryrefslogtreecommitdiff
path: root/src/lib/services/aitranslation.ts
blob: 331e10ed73a52610161ad5ab6fe663dc3af5d1e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import { z } from "zod";
import type { Language, TranslationService } from "../types";
import AIModelAPI, { type AIModelChoice } from "sortug-ai";
import type { AsyncRes } from "@/lib/types";

export class AiTranslator implements TranslationService {
  endpoint = ""; // doesn't apply here
  api;
  constructor(model: AIModelChoice) {
    const api = AIModelAPI(model);
    this.api = api;
  }

  async translate(
    text: string,
    sourceLang: string,
    targetLang: string,
  ): AsyncRes<string> {
    const input = [
      {
        author: "user",
        text: JSON.stringify({ text, sourceLang, targetLang }),
        sent: Date.now(),
      },
    ];
    const res = await this.api.send(
      `You are a professional, state of the art excellent translation service. Please translate the text given by the user. The prompts will be sent as JSON, in the format "{'text': string, 'sourceLang': string, 'targetLang': string}". You are to translate the 'text' from 'fromLang' to 'targetLang'. Output the desired translation and nothing else. Pause to think the translations as much as you need.`,
      input,
    );
    console.log({ res });
    if ("error" in res) return res;
    else return { ok: res.ok.join(", ") };
  }

  async getSupportedLanguages() {
    return { ok: [] };
  }
  async transliterate(
    text: string[],
    language: string,
    fromScript: string,
    toScript: string,
  ) {
    const input = [
      {
        author: "user",
        text: JSON.stringify({ text, language, fromScript, toScript }),
        sent: Date.now(),
      },
    ];
    const res = await this.api.send(
      `You are a professional, state of the art excellent translation service. Please transliterate, the text given by the user. The prompts will be sent as JSON, in the format "{'text': string, 'language': string, 'fromScript': string, 'toScript': string}". You are to transliterate the 'text' belongng to language 'language' from 'fromScript' to 'toScript' to the best of your ability. Output the desired transiteration and nothing else. Pause to think the output as much as you need.`,
      input,
    );
    if ("error" in res) return res;
    else return { ok: res.ok.join(", ") };
  }
}