Skip to content

Instantly share code, notes, and snippets.

@icai
Created March 7, 2023 02:50
Show Gist options
  • Save icai/402f7c403067f5926b5e01dd75e54068 to your computer and use it in GitHub Desktop.
Save icai/402f7c403067f5926b5e01dd75e54068 to your computer and use it in GitHub Desktop.
chatgpt GPT3 Translates Text.
const axios = require('axios');
class Base {
constructor(key, language, apiBase = null) {
this.key = key;
this.language = language;
this.currentKeyIndex = 0;
}
getKey(keyStr) {
const keys = keyStr.split(',');
const key = keys[this.currentKeyIndex];
this.currentKeyIndex = (this.currentKeyIndex + 1) % keys.length;
return key;
}
translate(text) {
throw new Error('translate method must be implemented by subclass');
}
}
class GPT3 extends Base {
constructor(key, language, apiBase = null) {
super(key, language);
this.apiKey = key;
this.apiUrl = apiBase ?
`${apiBase}v1/completions` :
'https://api.openai.com/v1/completions';
this.headers = {
'Content-Type': 'application/json',
};
// TODO support more models here
this.data = {
prompt: '',
model: 'text-davinci-003',
max_tokens: 1024,
temperature: 1,
top_p: 1,
};
this.session = axios.create();
this.language = language;
}
async translate(text) {
console.log(text);
this.headers.Authorization = `Bearer ${this.getKey(this.apiKey)}`;
this.data.prompt = `Please help me to translate,'${text}' to ${this.language}`;
try {
const response = await this.session.post(this.apiUrl, this.data, {
headers: this.headers,
});
if (response.status !== 200) {
throw new Error('API call failed');
}
const tText = response.data.choices[0].text.trim();
console.log(tText);
return tText;
} catch (error) {
console.error(error);
return text;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment