0%

Call ChatGPT API or chatgpt package in R

OpenAI于3月1日发布了ChatGPT API,但其只提供了Python中如何调用此API的文档说明。尽管没提到如何使用R来调用,但是毫无疑问R肯定是可以的,所以我用google搜了下。以下是基于网上资料而整理的简短介绍,如何在R中用ChatGPT。

直接调用API

本方法参考Call ChatGPT (or really any other API) from R,其于3月2号就发布了教程!

示例如下:

library(httr)
api_key <- "sk-Zzpcse7C0Mabe461NvEbToA3g765nYnmFwGgZ5b"
response <- POST(
  # curl https://api.openai.com/v1/chat/completions 
  url = "https://api.openai.com/v1/chat/completions", 
  # -H "Authorization: Bearer $OPENAI_API_KEY"
  add_headers(Authorization = paste("Bearer", api_key)),
  # -H "Content-Type: application/json"
  content_type_json(),
  # -d '{
  #   "model": "gpt-3.5-turbo",
  #   "messages": [{"role": "user", "content": "What is a banana?"}] 
  # }'
  encode = "json",
  body = list(
    model = "gpt-3.5-turbo",
    messages = list(list(role = "user", content = "How to use ChatGPT API in R?"))
  )
)

chatGPT_answer <- content(response)$choices[[1]]$message$content
chatGPT_answer <- stringr::str_trim(chatGPT_answer)
cat(chatGPT_answer)

首先在OpenAI API page创建一个API key,需要openai账号登陆

然后Create new secret key,会产生一个类似于上方示例代码中的sk-Zzpcse7C0Mabe461NvEbToA3g765nYnmFwGgZ5b等一连串字符(注意:示例代码的key是假的,无法使用,因为我基于我的修改了一些字符)

最后修改示例代码中的content后面的文字,输入你想要的即可实现与ChatGPT的交互。

此外你也可以打包成一个函数,方便调用,如:

# Calls the ChatGPT API with the given prompt and returns the answer
ask_chatgpt <- function(prompt) {
  response <- POST(
    url = "https://api.openai.com/v1/chat/completions", 
    add_headers(Authorization = paste("Bearer", api_key)),
    content_type_json(),
    encode = "json",
    body = list(
      model = "gpt-3.5-turbo",
      messages = list(list(
        role = "user", 
        content = prompt
      ))
    )
  )
  str_trim(content(response)$choices[[1]]$message$content)
}

answer <- ask_chatgpt("How to use ChatGPT API in R?")
cat(answer)

整体上还是蛮方便,对吧~

R package chatgpt

若问是否有ChatGPT 相关R包可供使用?可参考ChatGPT coding assistant for RStudio

其不仅提供了与ChatGPT交互的函数ask_chatgpt(),还有其他有意思功能,具体查看其文档说明即可!

使用也与上述API方法类似,也是先调用API key,然后选择对应的函数,但是会简洁一些,如:

Sys.setenv(OPENAI_API_KEY = "sk-Zzpcse7C0Mabe461NvEbToA3g765nYnmFwGgZ5b") # fake key, don't use it.

library(chatgpt)
cat(ask_chatgpt("How to use ChatGPT API in R?"))

*** ChatGPT input:

How to use ChatGPT API in R?
You can use the `httr` package in R to interact with ChatGPT's API. Here's a sample code to get started.

1. Install `httr` package via `install.packages("httr")`
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Load httr library
library(httr)

# Set the API parameters
url <- "https://api.chatgpt.com/chat"
body <- list(
query = "Hi, how are you?",
token = "<your-api-token>"
)

# Send a POST request to the endpoint
response <- POST(url, body = body)

# Extract the response content as a string
content(response, as = "text")
In this example, the `url` variable stores the endpoint URL of ChatGPT API. `body` has two parameters: - `query`: The text you want to send to ChatGPT API as input. - `token`: Your API token provided by ChatGPT. After setting the variables, the `POST` function from `httr` package sends a POST request to the API endpoint. Finally, the response content is extracted as a string using `content` function. Make sure to replace `<your-api-token>` with your ChatGPT API token before running the

ChatGPT 真是太神奇了~假如ChatGPT web版不崩的话,我还是会优先使用web版,因为现阶段我只为search而不是为了develop.