Call ChatGPT (or really any other API) from R (2024)

[This article was first published on R on Publishable Stuff, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

It’s March 2023 and right now ChatGPT, the amazing AI chatbot tool from OpenAI, is all the rage. But when OpenAI released their public web API for ChatGPT on the 1st of March you might have been a bit disappointed. If you’re an R user, that is. Because, when scrolling through the release announcement you find that there is a python package to use this new API, but no R package.

I’m here to say: Don’t be disappointed! As long as there is a web API for a service then it’s going to be easy to use this service from R, no specialized package needed. So here’s an example of how to use the new (as of March 2023) ChatGPT API from R. But know that when the next AI API hotness comes out (likely April 2023, or so) then it’s going to be easy to interface with that from R, as well.

To use the ChatGPT API in any way you first need to sign up and get an API key: The “password” you need to access the web API. It could look something like "sk-5xWWxmbnJvbWU4-M212Z2g5dzlu-MzhucmI5Yj-l4c2RkdmZ26". Of course, that’s not my real API key because that’s something you should keep secret!

With an API key at hand you now look up the documentation and learn that this is how you would send a request to the API from the terminal:

curl https://api.openai.com/v1/chat/completions \ -H "Authorization: Bearer $OPENAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "What is a banana?"}] }'

But how do we send a request to the API using R? What we can do is to “replicate” this call using httr: a popular R package to send HTTP requests. Here’s how this request would be made using httr (with the curl lines as comments above the corresponding httr code)

library(httr)api_key <- "sk-5xWW-replace-with-your-own-api-key-RkdmZ26"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 = "What is a banana?")) ))

Even if you don’t know how curl and httr work you should be able to roughly see what’s going on here. The response now contains the metadata and the content of the response from ChatGPT which you access like so:

content(response)$id[1] "chatcmpl-6q4RKjGkL8YLsEZNgeG1GA0Mb6mus"$object[1] "chat.completion"$created[1] 1677868142$model[1] "gpt-3.5-turbo-0301"$usage$usage$prompt_tokens[1] 14$usage$completion_tokens[1] 122$usage$total_tokens[1] 136$choices$choices[[1]]$choices[[1]]$message$choices[[1]]$message$role[1] "assistant"$choices[[1]]$message$content[1] "\n\nA banana is a type of fruit that is usually elongated andcurved, with a soft, sweet flesh inside a yellow or green skin.Bananas are rich in vitamins, minerals, fiber, and antioxidants, andare a popular food around the world. They can be eaten raw, cooked,or baked in a variety of dishes. Bananas are also used to makedrinks, smoothies, and desserts such as banana bread, banana pudding,and banana split."$choices[[1]]$finish_reason[1] "stop"$choices[[1]]$index[1] 0

Buried in this response is the actual answer which we can extract, clean up (ChatGPT seems to start every answer with a double linebreak, for some reason), and print out:

chatGPT_answer <- content(response)$choices[[1]]$message$contentchatGPT_answer <- stringr::str_trim(chatGPT_answer)cat(chatGPT_answer)A banana is a type of fruit that is usually elongated and curved, with a soft,sweet flesh inside a yellow or green skin. Bananas are rich in vitamins,minerals, fiber, and antioxidants, and are a popular food around the world.They can be eaten raw, cooked, or baked in a variety of dishes. Bananas arealso used to make drinks, smoothies, and desserts such as banana bread,banana pudding, and banana split.

And that’s it! Now you have the latest and greatest AI powers at your fingertips in R! There are many more things you can do with the ChatGPT API (setting up elaborate prompts, continuing earlier conversations, etc.) but all are possible through a variant of the httr::POST call above.

If all you want is to send simple one-off requests to ChatGPT here is all of the above wrapped up in a handy function:

# How to call the new (as of 2023-03-01) ChatGPT API from R# Get your API key over here: https://platform.openai.com/api_key <- "sk-5-your-actual-api-key-Fvau6" # Don't share this! 😅library(httr)library(stringr)# Calls the ChatGPT API with the given prompt and returns the answerask_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)}

Here’s how you could use it:

answer <- ask_chatgpt("What function makes a histogram in R?")cat(answer)The function that makes a histogram in R is "hist()".

Or why not use ChatGPT when you need some color inspiration? 🧟

fungal_green <- ask_chatgpt( "Answer only with the color hex code for 'fungal zombie green'")print(fungal_green)hist(rnorm(100), col = fungal_green)[1] "#8B956D"

Call ChatGPT (or really any other API) from R (1)

Related

To leave a comment for the author, please follow the link and comment on their blog: R on Publishable Stuff.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Call ChatGPT (or really any other API) from R (2024)

FAQs

Can you make API calls to ChatGPT? ›

Now we can construct a prompt for ChatGPT. Start with a clear and concise statement of what you need. For example, “I want to make API calls to the [x] API.” Follow this with a specific request to create a Python script with a function for each data source you're interested in.

Is there a free alternative to ChatGPT API? ›

Perplexity

Using the OpenAI API, Perplexity AI is an excellent alternative to ChatGPT. Designed following a minimalist interface, Perplexity offers a great conversational experience. You don't even have to create an account to use its free version, which is powered by Claude 3 Haiku.

Is GPT API better than ChatGPT? ›

I have noticed this issue since early days - but ChatGPT continues to perform much better than APIs.

Do I need ChatGPT Plus to use the API? ›

Please note that the ChatGPT Plus subscription does not include access to the ChatGPT API and are billed separately. The API has its own pricing, which can be found at https://openai.com/pricing. The ChatGPT Plus subscription covers usage on chatgpt.com only and costs $20/month.

Is it legal to use ChatGPT API? ›

According to OpenAI's Content Policy and Terms of Use, users of ChatGPT own all the output they create with the LLM, including text and images. Users are permitted to reuse, reprint, and sell ChatGPT-generated output, regardless of whether it was generated through a free plan, paid plan, or their API.

How much does it cost to use ChatGPT API? ›

So, for a business with 1,000 interactions per day, token usage could stretch to 100,000. That amounts to a daily ChatGPT API cost of $9: $3 for input and $6 for output instances. Businesses can also use AI chatbots to collect feedback from customers.

Is there a better AI than ChatGPT? ›

Best Overall: Anthropic Claude

Claude is the most human chatbot I've ever interacted with and with the addition of Claude 3.5 Sonnet and the new Artifacts feature — I use it more than ChatGPT. Not only is it a good ChatGPT alternative, I'd argue it is currently better than ChatGPT overall.

Is Bard better than ChatGPT? ›

In general, Bard is said to be better for research, while ChatGPT is said to be better for text generation.

Is GPT-4 more powerful than ChatGPT? ›

Both GPT-4 and ChatGPT leverage extensive datasets to learn patterns and generate responses. However, GPT-4 can handle real-time and up-to-date information better, enabling it to provide more relevant responses in dynamic contexts.

Is Bing GPT better than ChatGPT? ›

Is Bing AI the same as ChatGPT? No, Bing AI is subtly different from ChatGPT even if both are based on the same language model. In particular, you can expect longer and more creative responses from ChatGPT. Copilot, meanwhile, is meant to deliver informational responses first and foremost.

Is ChatGPT API pay as you go? ›

Our API service is billed and managed separately to ChatGPT. You'll be able to upgrade your API service to pay-as-you-go by adding a payment method in your API account billing settings. Note that API usage is charged by the number of tokens used. For more information, please see our pricing page.

Why would anyone pay for ChatGPT? ›

1. You need a greater message limit. After OpenAI supercharged the free version of its chatbot, the perks of subscription were less obvious. However, one of the biggest selling points of ChatGPT Plus is its greater message limit for users.

Can I use OpenAI API without paying? ›

Do I able to use API on the Free plan or not? Previously OpenAI gave free credits, but due to abuse or other reasons, they stopped. You'll need to drop in at least $5 to use it, I believe. If you have problems after paying, you can stop back by, and we can try to help you.

Which AI API is free to use? ›

Craiyon, formerly known as DALL-E mini, is a free AI image generator API that allows users to create unique images from text prompts. It is highly accessible and user-friendly, making it a popular choice for generating AI art through its free API service.

Can ChatGPT call external API? ›

It is possible to use APIs with GPTs. I successfully created an example of a GPT that incorporates additional logic from an external server.

How to hit ChatGPT API using postman? ›

Get Started with the ChatGPT API
  1. Overview. This is a beginner's introduction to OpenAI's API in Postman. ...
  2. Fork the OpenAI collection. Sign in to your Postman account. ...
  3. Authorization. Update the collection variable token with your own OpenAI API key. ...
  4. Make an API call with Postman. ...
  5. Generate a code sample. ...
  6. Next Steps.

How do I call API in chatbot? ›

Setting Up API Calls in Your Chatbot

Go to the chatbot dashboard. Here, you will find the Studio section that is your playground for developing and updating chatbot scenarios. In the studio, you can configure your chatbot to execute a range of activities based on user interactions.

How to train ChatGPT on your own data? ›

Train ChatGPT on Your Data in 3 Different Ways
  1. Step 1: First, sign up for LiveChatAI and sign in to your account. ...
  2. Step 2: Then, add your data source. ...
  3. Step 3: Choose pages and import your custom data. ...
  4. Step 4: Activate/ Deactivate human-supported live chat. ...
  5. Step 5: Finally, your AI chatbot will be created!

Top Articles
child care worker assistant - Montréal, QC - Job posting
Bullhead City, AZ | 3 bed house for rent #123938698 | Rentberry
Devin Mansen Obituary
AMC Theatre - Rent A Private Theatre (Up to 20 Guests) From $99+ (Select Theaters)
Average Jonas Wife
Jazmen Jafar Linkedin
Fort Carson Cif Phone Number
Chalupp's Pizza Taos Menu
What is international trade and explain its types?
Aces Fmc Charting
Gwdonate Org
Diesel Mechanic Jobs Near Me Hiring
Best Suv In 2010
Star Wars: Héros de la Galaxie - le guide des meilleurs personnages en 2024 - Le Blog Allo Paradise
The Grand Canyon main water line has broken dozens of times. Why is it getting a major fix only now?
Gayla Glenn Harris County Texas Update
*Price Lowered! This weekend ONLY* 2006 VTX1300R, windshield & hard bags, low mi - motorcycles/scooters - by owner -...
Project, Time & Expense Tracking Software for Business
Rufus Benton "Bent" Moulds Jr. Obituary 2024 - Webb & Stephens Funeral Homes
Sussyclassroom
Nsa Panama City Mwr
Valic Eremit
Weve Got You Surrounded Meme
Walgreens Bunce Rd
TeamNet | Agilio Software
Bolsa Feels Bad For Sancho's Loss.
Tokyo Spa Memphis Reviews
Summoners War Update Notes
Delete Verizon Cloud
Ncal Kaiser Online Pay
Rugged Gentleman Barber Shop Martinsburg Wv
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
Urban Blight Crossword Clue
Song That Goes Yeah Yeah Yeah Yeah Sounds Like Mgmt
Xemu Vs Cxbx
Top-ranked Wisconsin beats Marquette in front of record volleyball crowd at Fiserv Forum. What we learned.
Avance Primary Care Morrisville
Telegram update adds quote formatting and new linking options
Weapons Storehouse Nyt Crossword
Game8 Silver Wolf
5 Tips To Throw A Fun Halloween Party For Adults
Husker Football
Lbl A-Z
Windshield Repair & Auto Glass Replacement in Texas| Safelite
Smite Builds Season 9
Ssc South Carolina
Learn4Good Job Posting
Unblocked Games 6X Snow Rider
Race Deepwoken
Compete My Workforce
Vt Craiglist
Invitation Quinceanera Espanol
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 5363

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.