How can I execute a cURL command to interact with the OpenAI API in a Colab notebook?

I am executing the following code in Colab notebook:

!curl https://api.openai.com/v1/chat/completions
-H “Content-Type: application/json”
-H “Authorization: Bearer $OPENAI_API_KEY”
-d ‘{
“model”: “gpt-3.5-turbo”,
“messages”: [{“role”: “user”, “content”: “Say this is a test!”}],
“temperature”: 0.7
}’

I got the following error:
File “”, line 5
}’
^
SyntaxError: unmatched ‘}’

---- Verify the Existence of curl as Follows ----
commands:
!compgen -c |grep curl |sort -u
!cat /etc/os-release |grep PRETTY_NAM

result:
curl
curl-config
PRETTY_NAME=“Ubuntu 22.04.3 LTS”

hi!

why not use python, if you’re already in a python notebook?

this is for embeddings what I have at hand, but you get the gist

from urllib import request, parse
import json
import os

def get_openai_embedding(input_text, model="text-embedding-ada-002"):
    """
    Fetches the embedding for the given input text using OpenAI's API.

    Parameters:
    input_text (str): The text string to be embedded.
    model (str): The model to use for embedding. Default is 'text-embedding-ada-002'.

    Returns:
    list: The embedding vector, or None if an error occurs.
    """
    api_key = os.getenv('OPENAI_API_KEY') # your api key here
    url = 'https://api.openai.com/v1/embeddings'

    headers = {
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json'
    }

    data = {
        'input': input_text,
        'model': model
    }

    data = json.dumps(data).encode('utf-8')

    req = request.Request(url, data=data, headers=headers, method='POST')

    try:
        with request.urlopen(req) as response:
            response_body = response.read()
            embedding = json.loads(response_body)['data'][0]['embedding']
            return embedding
    except Exception as e:
        print(f'An error occurred: {e}')
        return None

# Example usage:
embedding = get_openai_embedding("Example text")
print(embedding)```

Thanks. I am indeed using python, which is fine for me without any issue. I am just exploring available alternatives.

The issue seems to be that Google Colab may have some issues with the multi-line continuation for shell commands using the ! operator.

Therefore, pythorn may be used to run curl command in colab:

#the Python subprocess module to run the curl command:

import subprocess

command = ‘’’
curl https://api.openai.com/v1/chat/completions
-H “Content-Type: application/json”
-H “Authorization: Bearer $OPENAI_API_KEY”
-d ‘{
“model”: “gpt-3.5-turbo”,
“messages”: [{“role”: “user”, “content”: “Say this is a test!”}],
“temperature”: 0.7
}’
‘’’

#the Python subprocess module to run the curl commandRun the command using subprocess and capture the output
result = subprocess.run(command, shell=True, capture_output=True)

#Print the output
print(result.stdout.decode())

the ! magic is used for one line command.

for the multiple line command, use %%bash instead, for example

%%bash
curl -s https://api.openai.com/v1/chat/completions \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
      "model": "gpt-3.5-turbo",
      "messages": [
        {
          "role": "user", "content": "hello"
        }
      ]
    }'
2 Likes

Thank you very much.
Your solution is working fine with the response as below:

{
“id”: “chatcmpl-8USRc82MmKBKKNm5mGFeunaliGGVl”,
“object”: “chat.completion”,
“created”: 1702269872,
“model”: “gpt-3.5-turbo-0613”,
“choices”: [
{
“index”: 0,
“message”: {
“role”: “assistant”,
“content”: “Hello! How can I assist you today?”
},
“finish_reason”: “stop”
}
],
“usage”: {
“prompt_tokens”: 8,
“completion_tokens”: 9,
“total_tokens”: 17
},
“system_fingerprint”: null
}