Skip to content

Instantly share code, notes, and snippets.

@bogdan
Created March 8, 2024 13:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bogdan/b699fd0e084bec17ddca3dbc594f888b to your computer and use it in GitHub Desktop.
Save bogdan/b699fd0e084bec17ddca3dbc594f888b to your computer and use it in GitHub Desktop.
import fetch from "isomorphic-unfetch";

const translateToSQL = async (query, apiKey, tableSchema = "") => {

 // Validate inputs
 if (!query || !apiKey) {
   throw new Error("Missing query or API key.");
 }

 const prompt = `Translate this natural language query into SQL without changing the case of the entries given by me:\n\n"${query}"\n\n${tableSchema ? `Use this table schema:\n\n${tableSchema}\n\n` : ''}SQL Query:`;
 
 console.log(prompt);
 const response = await fetch("https://api.openai.com/v1/completions", {
   method: "POST",
   headers: {
     "Content-Type": "application/json",
     Authorization: `Bearer ${apiKey}`,
   },
   body: JSON.stringify({
     prompt,
     temperature: 0.5,
     max_tokens: 2048,
     n: 1,
     stop: "\\n",
     model: "gpt-3.5-turbo-instruct",
     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 SQL.");
 }

 return data.choices[0].text.trim();
};

export default translateToSQL;
require 'net/http'
require 'uri'
require 'json'

def translate_to_sql(query, api_key, table_schema = "")
  # Validate inputs
  raise "Missing query or API key." if query.nil? || api_key.nil?

  prompt = "Translate this natural language query into SQL without changing the case of the entries given by me:\n\n\"#{query}\"\n\n#{table_schema.empty? ? '' : "Use this table schema:\n\n#{table_schema}\n\n"}SQL Query:"

  puts prompt

  uri = URI("https://api.openai.com/v1/completions")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new(uri)
  request["Content-Type"] = "application/json"
  request["Authorization"] = "Bearer #{api_key}"
  request.body = JSON.generate({
    prompt: prompt,
    temperature: 0.5,
    max_tokens: 2048,
    n: 1,
    stop: "\n",
    model: "gpt-3.5-turbo-instruct",
    frequency_penalty: 0.5,
    presence_penalty: 0.5,
    logprobs: 10
  })

  response = http.request(request)
  data = JSON.parse(response.body)

  if response.code.to_i >= 400
    puts "API Error: #{response.code}", data
    raise "Error translating to SQL: #{data['error']}"
  end

  data['choices'][0]['text'].strip
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment