[Python] How to translate Python into R to access API for Open AI?

Discussão em 'Python' iniciado por Stack, Maio 16, 2025.

  1. Stack

    Stack Membro Participativo

    I was given this code as an example how to access Open AI through API using Python:

    import requests
    import json
    url = "ENDPOINT"
    API_KEY = "SECRET_KEY"

    payload = json.dumps({
    "messages": [
    {
    "role": "system",
    "content": "You are an AI assistant named Genie the Genious that helps people find information from enterprise documents."
    },
    {
    "role": "user",
    "content": "how many faces does a cube have?"
    },
    {
    "role": "assistant",
    "content": "A cube has six faces."
    },
    {
    "role": "user",
    "content": "What is your name?"
    },
    {
    "role": "assistant",
    "content": ""
    }
    ],
    "temperature": 0.8,
    "top_p": 1,
    "frequency_penalty": 0,
    "presence_penalty": 0,
    "max_tokens": 60,
    "stop": None
    })
    headers = {
    'api-key': API_KEY,
    'Content-Type': 'application/json'
    }


    response = requests.request("POST", url, headers=headers, data=payload)


    I tried to translate this into R:

    library(httr)
    library(jsonlite)

    url = "ENDPOINT"
    api_key = "SECRET_KEY"

    # Create the payload as a JSON object
    payload <- toJSON(list(
    messages = list(
    list(
    role = "system",
    content = "You are an AI assistant named Genie the Genious that helps people find information from enterprise documents."
    ),
    list(
    role = "user",
    content = "how many faces does a cube have?"
    ),
    list(
    role = "assistant",
    content = "A cube has six faces."
    ),
    list(
    role = "user",
    content = "What is your name?"
    ),
    list(
    role = "assistant",
    content = ""
    )
    ),
    temperature = 0.8,
    top_p = 1,
    frequency_penalty = 0,
    presence_penalty = 0,
    max_tokens = 60,
    stop = NULL
    ), auto_unbox = TRUE)

    # Set the request headers
    headers <- add_headers(
    `api-key` = api_key,
    `Content-Type` = "application/json"
    )

    # Send the POST request to the API
    response <- POST(url, headers, body = payload)

    # Get the response content
    content <- content(response, as = "text")

    # Print the response
    cat(content)

    print(response)


    But I am getting this error:

    "error": {
    "message": "Invalid type for 'stop': expected one of a string or array of strings, but got an obje...
    "type": "invalid_request_error",
    "param": "stop",
    "code": "invalid_type" }


    It seems to have something to do with defining the payload but it is not clear to me how this can be modified so it can be recognised in the system through R?

    Any pointers greatly appreciated, I suspect this is not a hard question just need to get the format correct.

    Continue reading...

Compartilhe esta Página