Calling APIs and using secrets

There are thousands of APIs we can call from Python and doing so from within Google Sheets using Neptyne is a great way to get access to sheer infinite extensibility. Some APIs are free whether after registering or not. Other APIs you need to pay for and those often require you to provide a key when calling them. One of the most popular APIs in the last category is of course OpenAI. Let’s do some ChatGPT in a Google Sheet!

First thing is to register at OpenAI and get a key. If you haven’t already done this, sign up, then head over to your api keys and create a new one.

Now open a new google sheet, and open the Neptyne code editor and enter the following code:

import openai
import neptyne as nt


def call_open_ai(prompt):
    openai.api_key = nt.get_secret("open-ai-key")
    completion = openai.ChatCompletion.create(
        model="gpt-3.5-turbo", 
        messages=[{"role": "user", 
        "content": prompt}]
    )
    choices = completion.get("choices")
    if not choices:
        return None
    return choices[0]["message"]["content"]

We don’t enter the api key directly in the code; instead we’re getting this from the neptyne secret management. Go to the Neptyne menu and choose the Manage Secrets. Create a new secret, call it “open-ai-key” and enter as the value the api key you got from OpenAI.

To verify this all works, enter in the REPL (the entry box under the code editor) call_open_ai(“what is the capital of France”) and you should see Paris:

Let’s create an app that uses this API to create a recipe. We’ll use as inputs what we are making, how long we have to make it, and a list of ingredients. Add this to the spreadsheet like this:

Next add the following code to use OpenAI to generate a recipe:

def create_recipe(what, pre_time, ingredients):
    prompt = (
        "Given this ingredients:\n\n"
        + ", ".join(ingredients)
        + " Create a recipe for "
        + what
        + " that takes "
        + pre_time
        + " to prepare."
    )
    return call_open_ai(prompt)

And in E1 add this formula:

=Py("create_recipe", C1, C2, C3:C17)

It will take a few seconds, but you should see your recipe. Adjust the size of the cell by merging it with neighbors to get a reasonably sized working area and now your cooking!

Congratulations, you've finished the introductory tutorials!

Check out the Application Gallery to see more examples of how you can bring the power of Python into your spreadsheets!

For more tutorials, continue to Advanced Features Tutorials.