← All Apps Scripts templates
Return country code from an address

Return country code from an address

  1. Create a new Google Sheets file
  2. Go to Extensions → Apps Script
  3. Remove all the code and copy-paste the following instead
  4. Sign-Up to Open AI https://beta.openai.com/signup
  5. Once you have an account, get your API key.
  6. Click on your name in the top-right corner
  7. Click on view API Keys
  8. Create new secret key
  9. Copy the key
  10. Paste your key inside your Apps Script project.
  11. Make sure it looks like "sk-2decdcdvfedf"
  12. Save your project and go back to your sheet
  13. Use =runOpenAI(), like classic Google Sheets Formula and insert your prompt

The new formula in Google Sheets:


A few examples of prompts:

=runOpenAI("Normalize company names. Remove legal entity names.
Apple 😎:Apple
Google LLC 🔥:Google
Facebook corp.:Facebook
", E2)

=runOpenAI("Categorize job title by seniority.
Head of Sales:Senior
", H2)

=runOpenAI("Classify the email response. Can be either 'interested', 'not interested'
I'd love to know more about it:interested
No thank you:not interested

=runOpenAI("extract domain from email.Answer 'true' if domain is an email provider or 'false' if not. Don't return domain.

=runOpenAI("Give Country from Address.Return a country code.

4 Priory Close, Birmingham, United Kingdom: GB
12 San Francisco, California, USA: US
24 Rue Notre-Dame, Montreal, Canada: CA
22 Piazza del Popolo, Rome: IT

The code to paste in Apps Script inside Google Sheets:

 * Generates text using OpenAI's GPT-3 model
 * @param {string} prompt The prompt to feed to the GPT-3 model
 * @param {string} cell The cell to append to the prompt
 * @param {number} [maxWords=10] The maximum number of words to generate
 * @return {string} The generated text
 * @customfunction

function runOpenAI(prompt, cell, maxWords) {


maxTokens = 10
if (maxWords){maxTokens = maxWords * 0.75}

model = "text-davinci-003"
prompt = prompt+cell+":",
temperature= 0

  // Set up the request body with the given parameters
  const requestBody = {
    "model": model,
    "prompt": prompt,
    "temperature": temperature,
    "max_tokens": maxTokens

  // Set up the request options with the required headers
  const requestOptions = {
    "method": "POST",
    "headers": {
      "Content-Type": "application/json",
      "Authorization": "Bearer "+API_KEY
    "payload": JSON.stringify(requestBody)

  // Send the request to the GPT-3 API endpoint for completions
  const response = UrlFetchApp.fetch("https://api.openai.com/v1/completions", requestOptions);

  // Get the response body as a JSON object
  const responseBody = JSON.parse(response.getContentText());

  let answer= responseBody.choices[0].text

  // Return the generated text from the response
  return answer

Reach us if the process is unclear or if the script is outdated
Apps Scripts template

Return country code from an address

Last updated
Built by
Avatar Placeholder