Skip to main content
Photo of DeepakNess DeepakNess

Connect OpenRouter API to Google Sheets

Unproofread notes

If you quickly want to connect OpenRouter API inside Google Sheets then here is an Apps Script function that you can directly use. There are 100s of AI models from OpenAI, Claude, Gemini, and more that you can use via a single API.

function OPENROUTER(prompt) {
  var API_KEY = 'PUT_YOUR_OPENROUTER_API_KEY_HERE';
  var MODEL = 'openrouter/auto'; // or a specific model id

  if (!API_KEY || API_KEY === 'PUT_YOUR_OPENROUTER_API_KEY_HERE') {
    throw new Error('Set your API key in the script first.');
  }
  if (!prompt) {
    throw new Error('Missing prompt.');
  }

  var endpoint = 'https://openrouter.ai/api/v1/chat/completions';

  var payload = {
    model: MODEL,
    messages: [{ role: 'user', content: String(prompt) }],
    max_tokens: 1000,
    temperature: 0.7
  };

  var options = {
    method: 'post',
    contentType: 'application/json',
    payload: JSON.stringify(payload),
    headers: {
      'Authorization': 'Bearer ' + API_KEY,
      'HTTP-Referer': 'https://script.google.com',
      'X-Title': 'Google Sheets Script'
    },
    muteHttpExceptions: true
  };

  var response = UrlFetchApp.fetch(endpoint, options);
  var code = response.getResponseCode();
  var text = response.getContentText();

  var json;
  try {
    json = JSON.parse(text);
  } catch (e) {
    throw new Error('Bad JSON response (' + code + '): ' + text.slice(0, 300));
  }

  if (code !== 200) {
    var apiMsg = json && json.error ? (' ' + (json.error.message || JSON.stringify(json.error))) : '';
    throw new Error('OpenRouter error ' + code + '.' + apiMsg);
  }

  if (json && json.choices && json.choices[0] && json.choices[0].message && typeof json.choices[0].message.content === 'string') {
    return json.choices[0].message.content;
  }

  throw new Error('No content in response: ' + text.slice(0, 300));
}

While this works for a simple use case, if you have to process 100s and even 1000s of rows then you'll need a more robust script that can keep working in the background. And just so you know, InvertedStone has a script that can do exactly that.

The best thing is the script is always updated with new features and abilities, for example, it can now read images, PDFs, webpages, and has internet access as well. And can also generate images using different image generation models.

Comment via email