Davinci-002 & Google Sheets Question... (AKA Am I doing it wrong?!)

Hi All,

Does anyone have any experience with Google Sheets and the API?

I’ve written some code…no, I got the AI to write it (eventually!) in Python that uses the Google API to search a Google Drive folder for all the Sheets contained within and spit out all of their IDs.

I’m then asking Davinci to make a short (50 words or so) summary of what’s in the sheet, then write that to a text file, then iterate through all of the IDs and append the doc with the summary.

I’m finding that the AI has a problem doing a summary It appears to have access to the sheet (don’t know how I’d confirm for sure though), But the summary that I get back is basically an Ipsum Locum - it doesn’t have anything to do with the sheet at all. I’ve asked it do a single sheet in case it’s an iteration problem, but no, it appears not. It seems to be able to access something, because one of the early prompts was taken very literally and it just returned some cell reference hyperlinks in the summary.

There’s enough information in the column headers to have a pretty good idea what the sheet is ‘about’, so I’m not entirely sure what’s going on,or why, and I was hoping someone here may be able to shed some light?

I’m happy to share the code if it helps.

Thanks in advance!

Yeah, would likely need to see some code to help. Sounds like GPT-3 API is not getting the proper info for your prompt. Are you just sending the raw data without constructing a “prompt” at all with it?

Someone just shared a spreadsheet integration the other day, I believe.

Thanks for the reply Paul. No, I’m putting out prompts - I’ve tried changing them a number of times. I get some variety in the replies, but consistent within a ‘type’ of prompt.

Please excuse the code, but here it is:

import os
import json
import datetime

import httplib2
import googleapiclient.discovery
import googleapiclient.errors
import google_auth_oauthlib.flow
from google.oauth2.credentials import Credentials

import openai

Replace YOUR_FOLDER_ID with the actual folder ID

folder_id = “Folderwheregoogleslive”

Replace YOUR_API_KEY with your actual OpenAI API key

openai.api_key = “Ivedeletedthekeybutyesitworrks”

Use the client_secret.json file to identify the application requesting

authorization. The client ID (from that file) and access scopes are required.

flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'theres_a_secret_file_here_but_I’m censoring])

Indicate where the API server will redirect the user after the user completes

the authorization flow.

flow.redirect_uri = ‘urn:ietf:wg:oauth:2.0:oob’

Generate the authorization URL

authorization_url, state = flow.authorization_url(
access_type=‘offline’,
include_granted_scopes=‘true’)

Print the authorization URL and state

print(f"Authorization URL: {authorization_url}“)
print(f"State: {state}”)

Prompt the user to open the authorization URL in their browser and enter the

authorization code.

print(“Please open the following URL in your browser and enter the authorization code:”)
print(authorization_url)

Get the authorization code from the user

authorization_code = input("Enter the authorization code: ")

Use the authorization code to fetch the access token

flow.fetch_token(code=authorization_code)

Get the access token

creds = flow.credentials

Create a service object that you can use to make requests to the Google Drive API

service = googleapiclient.discovery.build(“drive”, “v3”, credentials=creds)

def get_sheets_in_folder(folder_id, service):
sheets =
try:
# List all files in the specified folder
page_token = None
while True:
response = service.files().list(q=f"‘{folder_id}’ in parents",
spaces=‘drive’,
fields='nextPageToken, ’
‘files(id, mimeType)’,
pageToken=page_token).execute()
for file in response.get(‘files’, ):
# If the file is a Google Sheets file, add it to the list
if file.get(‘mimeType’) == ‘application/vnd.google-apps.spreadsheet’:
sheets.append(file.get(‘id’))
page_token = response.get(‘nextPageToken’, None)
if page_token is None:
break
except HttpError as error:
print(f"An error occurred: {error}")
return sheets

Call the function to get the list of sheets in the specified folder

sheets = get_sheets_in_folder(folder_id, service)

Print the list of sheets

print(f"Sheets in folder {folder_id}:")
for sheet in sheets:
print(sheet)

Create a list to store the summaries

summaries =

Use the OpenAI API to generate summaries of the sheets

def summarize_sheet(sheet_id, num_rows):
# Print some debugging information
print(f"Generating summary for sheet {sheet_id} with {num_rows} rows")

# Use the OpenAI API to generate a summary of the sheet
model_engine = "text-davinci-002"
prompt = (f"Promptstringgoeshere: Sheet ID: {sheet_id}. "
         f"Include the first {num_rows} rows in the summary.")

completions = openai.Completion.create(
    engine=model_engine,
    prompt=prompt,
    max_tokens=1024,
    n=1,
    stop=None,
    temperature=0.5,
)

message = completions.choices[0].text

# Print some debugging information
print(f"Summary for sheet {sheet_id}: {message}")

return message

Iterate over the list of sheets

for i, sheet in enumerate(sheets):
# Print a progress update
print(f"Processing sheet {i+1} of {len(sheets)}")

# Make sure the sheet is a dictionary before trying to access its attributes
if isinstance(sheet, dict):
    sheet_id = sheet.get('id')
    num_rows = 10  # Start with the first 10 rows
    summary = ""
    while not summary:  # Keep increasing the number of rows until we get a summary
        summary = summarize_sheet(sheet_id, num_rows)
        num_rows += 10

    # Append the summary to the list
    summaries.append(summary)

Create the filename

filename = f"summaries_{datetime.datetime.now().strftime(‘%Y-%m-%d_%H-%M-%S’)}.txt"

Open the file in write mode

with open(filename, “w”) as file:
# Write each summary to the file
for summary in summaries:
file.write(summary + “\n”)

Print a message to the user

print(f"Summaries written to {filename}")

I’ve tried all kinds of prompts from the simplest ‘does this word exist in row A’ to much more convoluted things.

Can you give an example of what the prompt looks like after it comes out of the code?

ETA: The temp might be a bit too low too…