Editing script to integrate OPENAI api with airtable without any 3rd party apps (need help)

660 0
Showing results for 
Search instead for 
Did you mean: 
4 - Data Explorer
4 - Data Explorer

Hello guys, I need some help in editing the below code to integrate open ai api with airtable directly without any 3rd party tools. is there any way that we can make the script automatically run all records of a column instead of manually selecting each column every time. 



const {
} = input.config({
    title: "Connector to OpenAI API - Using text-davinci-003",
    description: "",
    items: [
        input.config.table("table", {
            label: "Table",
            description: "Where your fields are"
        input.config.field("promptField", {
            parentTable: "table",
            label: "Prompt Field",
            description: "Text you want a response to"
        input.config.field("outputField", {
            parentTable: "table",
            label: "Output Field",
            description: ""
        input.config.text("openaiApiKey", {
            label: "OpenAI API Key",
            description: "Get it from"
        input.config.text("maxTokensStr", {
            label: "Max Tokens",
            description: "Max: 4,097 tokens. A helpful rule of thumb is that one token generally corresponds to ~4 characters of text for common English text. This translates to roughly ¾ of a word (so 100 tokens ~= 75 words)."

if (!Number(maxTokensStr)) {
    throw "Max Tokens must be a number"

if(promptField.type != "singleLineText" && promptField.type != "multilineText"){
    throw "Prompt field must be a single line text or long text field"

if(outputField.type != "singleLineText" && outputField.type != "multilineText"){
    throw "Output field must be a single line text or long text field"

const maxTokens = Number(maxTokensStr);

const record = await input.recordAsync("Pick a record", table);

const userInput = record.getCellValueAsString(promptField);

if (!userInput) {
    throw "Error: Prompt is empty"

let response;
try {
    response = await getGPTResponse(userInput);
} catch (error) {
    throw "Error: Failed to get GPT response"

output.markdown(`Received Prompt: **${userInput}**`);
output.markdown(`Response: **${response}**`);

const updates = [{
    id: record?.id,
    fields: {
        []: response

while (updates.length > 0) {
    await table.updateRecordsAsync(updates.slice(0, 50));
    updates.splice(0, 50);

async function getGPTResponse(userInput) {
  const prompt = `The following is a conversation with an AI assistant. The assistant is helpful, creative, clever, and very friendly.\n\nUser: ${userInput}\nAI:`;
  const response = await fetch('', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${openaiApiKey}`,
    body: JSON.stringify(
          "model": "text-davinci-003",
          "prompt": prompt,
          "max_tokens": maxTokens,
          "temperature": 0

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status} - ${response.statusText}`);

  const responseData = await response.json();
  return responseData.choices[0].text.trim();

function getHTTPStatusHelpText(statusCode) {
  switch (statusCode) {
    case 400:
      return "Bad Request: The server cannot understand the request due to invalid syntax.";
    case 401:
      return "Unauthorized: Authentication is required and has failed or has not yet been provided.\n\nPlease double check your API key";
    case 402:
      return "Payment Required: The request cannot be processed until a payment is made.";
    case 403:
      return "Forbidden: The server understood the request, but is refusing to fulfill it.";
    case 404:
      return "Not Found: The requested resource could not be found but may be available in the future.";
    case 429:
      return "Too Many Requests: The user has sent too many requests in a given amount of time.\n\nDo you still have credits in your account?";
    case 500:
      return "Internal Server Error: The server has encountered a situation it doesn't know how to handle.";
    case 502:
      return "Bad Gateway: The server was acting as a gateway or proxy and received an invalid response from the upstream server.";
    case 503:
      return "Service Unavailable: The server is currently unable to handle the request due to a temporary overload or maintenance.";
      return "Unknown HTTP status code.";


0 Replies 0