Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update translateToHuman.js #62

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 37 additions & 25 deletions src/translateToHuman.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,35 +3,47 @@ import fetch from "isomorphic-unfetch";
const translateToHuman = async (query, apiKey) => {
// Validate inputs
if (!query || !apiKey) {
throw new Error("Missing query or API key.");
throw new Error("Both query and API key are required.");
}

const response = await fetch("https://api.openai.com/v1/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
prompt: `Translate this SQL query into natural language:\n\n"${query}"\n\nNatural language query:`,
temperature: 0.5,
max_tokens: 2048,
n: 1,
stop: "\\n",
model: "text-davinci-003",
frequency_penalty: 0.5,
presence_penalty: 0.5,
logprobs: 10,
}),
});
// Construct the API request payload
const payload = {
prompt: `Translate the following SQL query into natural language:\n\n"${query}"\n\nNatural language query:`,
temperature: 0.5,
max_tokens: 2048,
n: 1,
stop: "\\n",
model: "text-davinci-003",
frequency_penalty: 0.5,
presence_penalty: 0.5,
logprobs: 10,
};

const data = await response.json();
if (!response.ok) {
console.error("API Error:", response.status, data);
throw new Error(data.error || "Error translating to human language.");
}
try {
// Make the API request
const response = await fetch("https://api.openai.com/v1/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify(payload),
});

// Check for API errors
if (!response.ok) {
const errorData = await response.json();
console.error("API Error:", response.status, errorData);
throw new Error(errorData.error?.message || "Error translating query to natural language.");
}

return data.choices[0].text.trim();
// Parse and return the response
const { choices } = await response.json();
return choices[0]?.text?.trim() || "No translation available.";
} catch (error) {
console.error("Request Error:", error);
throw new Error("Error processing the request.");
}
};

export default translateToHuman;