irudnyts / openai

An R package-wrapper around OpenAI API
https://irudnyts.github.io/openai/
Other
164 stars 28 forks source link

Implement Chat endpoint #29

Closed irudnyts closed 1 year ago

irudnyts commented 1 year ago

See https://platform.openai.com/docs/api-reference/chat for details.

zhaohongxin0 commented 1 year ago

How to use gpt-3.5-turbo in R? Need to update the openai package?

mpr1255 commented 1 year ago

I wonder if all that needs to be done is just change

base_url <- glue::glue("https://api.openai.com/v1/{task}")

to

base_url <- glue::glue("https://api.openai.com/v1/chat/{task}")

in

https://github.com/irudnyts/openai/blob/main/R/create_completion.R

When the model is one of the new gpt-3.5-turbo versions?

zhaohongxin0 commented 1 year ago

I wonder if all that needs to be done is just change

base_url <- glue::glue("https://api.openai.com/v1/{task}")

to

base_url <- glue::glue("https://api.openai.com/v1/chat/{task}")

in

https://github.com/irudnyts/openai/blob/main/R/create_completion.R

When the model is one of the new gpt-3.5-turbo versions?

But the parameters may not be same. Gpt-3.5-turbo has role of system and user.

irudnyts commented 1 year ago

It is actually almost done and you can check out the code in the chat-audio branch: https://github.com/irudnyts/openai/blob/chat-audio/R/create_chat_completion.R. If you want to use it right now, you can install it via remotes::install_github("irudnyts/openai", ref = "chat-audio"). Otherwise, in a couple of days, the package will be available from CRAN.

And you're right, it is just a different endpoint address and a different set of the function's parameters.

zhaohongxin0 commented 1 year ago

chatGPT itself told me how to use this in R:

library(httr) library(jsonlite)

api_key <- "OPENAI_API_KEY"

response <- POST( url = "https://api.openai.com/v1/chat/completions", add_headers(Authorization = paste("Bearer", api_key)), body = list( model = "gpt-3.5-turbo", messages = list( list(role = "user", content = "Hello world") ) ), encode = "json" )

result <- content(response, as = "text") parsed_result <- fromJSON(result)

answer <-parsed_result$choices[[1]]$content

It really works!

irudnyts commented 1 year ago

Right, and that's how create_chat_completion() works in a nutshell.

irudnyts commented 1 year ago

Good news, everyone! I have updated the package on CRAN, and the function create_chat_completion() is available from that installation.