on-internet
← Community

OpenAI API: How to count tokens before API request

Stack Overflow ·

I would like to count the tokens of my OpenAI API request in R before sending it (version gpt-3.5-turbo). Since the OpenAI API has rate limits, this seems important to me. Example: The function I use to send requests: 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) } Example api_key <- "your_op

Comments

Sign in or sign up to comment and upvote.

No comments yet.