m2geval / r /chatgpt_function_bench.jsonl
Tswatery's picture
Add files using upload-large-folder tool
f18999e verified
Raw
History Blame Contribute Delete
122 kB
{"repo_name": "chatgpt", "file_name": "/chatgpt/R/generate_image.R", "inference_info": {"prefix_code": "#' Generate an Image With DALL-E 3\n#'\n#' @param prompt The prompt for image generation.\n#' @param out_file The path where to save the generated image.\n#' @param openai_api_key OpenAI's API key.\n#'\n#' @importFrom httr add_headers content content_type_json POST stop_for_status\n#' @importFrom jsonlite fromJSON toJSON\n#' @importFrom utils download.file\n#'\n#' @export\n#'\ngenerate_image <- ", "suffix_code": "\n", "middle_code": "function(prompt, out_file = tempfile(fileext = \".png\"),\n openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n post_res <- POST(\n paste0(api_url, \"/images/generations\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = toJSON(\n list(model = \"dall-e-3\", prompt = prompt, n = 1, size = \"1024x1024\"),\n auto_unbox = TRUE\n )\n )\n stop_for_status(post_res)\n download.file(fromJSON(content(post_res, as = \"text\", encoding = \"UTF-8\"))$data$url, out_file)\n return(out_file)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/chatgpt/R/list_models.R", "#' ChatGPT: List Models\n#'\n#' @param openai_api_key OpenAI's API key.\n#'\n#' @examples\n#' \\dontrun{\n#' list_models()\n#' }\n#'\n#' @importFrom httr add_headers content GET stop_for_status\n#' @importFrom jsonlite fromJSON\n#'\n#' @return A data.frame with the available models to be used by OpenAI's API.\n#'\n#' @export\n#'\nlist_models <- function(openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n get_res <- GET(\n paste0(api_url, \"/models\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key))\n )\n stop_for_status(get_res)\n fromJSON(content(get_res, as = \"text\", encoding = \"UTF-8\"))$data\n}\n"], ["/chatgpt/R/gpt_get_completions.R", "#' Get GPT Completions Endpoint\n#'\n#' @param prompt The prompt to generate completions for.\n#' @param openai_api_key OpenAI's API key.\n#' @param messages Available variable, to send the needed messages list to ChatGPT.\n#'\n#' @importFrom httr add_headers content content_type_json POST use_proxy\n#' @importFrom jsonlite toJSON\n#'\ngpt_get_completions <- function(prompt, openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"),\n messages = NULL) {\n if (nchar(openai_api_key) == 0) {\n stop(\"`OPENAI_API_KEY` not provided.\")\n }\n # See https://platform.openai.com/docs/api-reference/chat .\n params <- list(\n model = Sys.getenv(\"OPENAI_MODEL\", \"gpt-4o-mini\"),\n max_tokens = as.numeric(Sys.getenv(\"OPENAI_MAX_TOKENS\", 256)),\n temperature = as.numeric(Sys.getenv(\"OPENAI_TEMPERATURE\", 1)),\n top_p = as.numeric(Sys.getenv(\"OPENAI_TOP_P\", 1)),\n frequency_penalty = as.numeric(Sys.getenv(\"OPENAI_FREQUENCY_PENALTY\", 0)),\n presence_penalty = as.numeric(Sys.getenv(\"OPENAI_PRESENCE_PENALTY\", 0)),\n logprobs = as.logical(Sys.getenv(\"OPENAI_LOGPROBS\", FALSE))\n )\n if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT input:\\n\\n\", prompt, \"\\n\"))\n }\n return_language <- Sys.getenv(\"OPENAI_RETURN_LANGUAGE\")\n if (nchar(return_language) > 0) {\n return_language <- paste0(\"You return all your replies in \", return_language, \".\")\n }\n if (is.null(messages)) {\n messages <- list(\n list(\n role = \"system\",\n content = paste(\n \"You are a helpful assistant with extensive knowledge of R programming.\",\n return_language\n )\n ),\n list(role = \"user\", content = prompt)\n )\n } else {\n # If there are messages provided, then add the `return_language` if available.\n messages[[which(sapply(messages, function(message) message$role == \"system\"))]]$content <-\n paste(\n messages[[which(sapply(messages, function(message) message$role == \"system\"))]]$content,\n return_language\n )\n }\n # Get the proxy to use, if provided.\n proxy <- NULL\n if (nchar(Sys.getenv(\"OPENAI_PROXY\")) > 0) {\n proxy <- Sys.getenv(\"OPENAI_PROXY\")\n if (grepl(\"^(?:\\\\d{1,3}\\\\.){3}\\\\d{1,3}:\\\\d{2,5}$\", proxy)) {\n proxy <- use_proxy(gsub(\":.*\", \"\", proxy), as.numeric(gsub(\".*:\", \"\", proxy)))\n } else {\n stop(\"Invalid proxy provided in `OPENAI_PROXY`: \", proxy)\n }\n }\n # Run the API query.\n final_res <- list()\n keep_querying <- TRUE\n while (keep_querying) {\n post_res <- POST(\n paste0(api_url, \"/chat/completions\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = toJSON(c(params, list(messages = messages)), auto_unbox = TRUE),\n proxy\n )\n if (!post_res$status_code %in% 200:299) {\n stop(content(post_res))\n }\n if (get_verbosity() > 1) {\n # If verbose is over 1, show the ongoing GPT response.\n message(content(post_res, as = \"text\", encoding = \"UTF-8\"))\n }\n post_res <- content(post_res)\n final_res <- append(final_res, list(post_res))\n # In the case the finish_reason is the length of the message, then we need to keep querying.\n keep_querying <- all(sapply(post_res$choices, function(x) x$finish_reason == \"length\"))\n # And update the messages sent to ChatGPT, in order to continue the current session.\n messages <- append(\n append(\n messages,\n list(list(role = \"assistant\", content = parse_response(list(post_res), verbosity = 0)))\n ),\n list(list(role = \"user\", content = \"continue\"))\n )\n }\n final_res\n}\n"], ["/chatgpt/R/ask_chatgpt.R", "#' Ask ChatGPT\n#'\n#' Note: See also `reset_chat_session`.\n#'\n#' @param question The question to ask ChatGPT.\n#' @param session_id The ID of the session to be used. We can have different conversations by using\n#' different session IDs.\n#' @param openai_api_key OpenAI's API key.\n#' @param images A list of images to attach to the question. It could be a list of URLs or paths.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(ask_chatgpt(\"What do you think about R language?\"))\n#' }\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nask_chatgpt <- function(question, session_id = \"1\", openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"),\n images = NULL) {\n # Get the existing chat session messages, and add the new message.\n chat_session_messages <- append(get_chat_session(session_id), list(\n list(role = \"user\", content = build_prompt_content(question, images))\n ))\n # Send the query to ChatGPT.\n chat_gpt_reply <- parse_response(\n gpt_get_completions(question, openai_api_key, chat_session_messages)\n )\n chat_session_messages <- append(chat_session_messages, list(\n list(role = \"assistant\", content = chat_gpt_reply)\n ))\n # Update the chat session messages with the new question and the reply.\n reset_chat_session(chat_session_messages, session_id)\n chat_gpt_reply\n}\n"], ["/chatgpt/R/addins.R", "#' Run a ChatGPT RStudio Addin\n#'\n#' @param addin_name The name of the adding to execute.\n#'\n#' @importFrom rstudioapi as.document_range getActiveDocumentContext modifyRange\n#'\nrun_addin <- function(addin_name) {\n # Select which addin has to be used.\n addin_function <- switch(addin_name,\n \"comment_code\" = comment_code,\n \"complete_code\" = complete_code,\n \"create_unit_tests\" = create_unit_tests,\n \"create_variable_name\" = create_variable_name,\n \"document_code\" = document_code,\n \"explain_code\" = explain_code,\n \"find_issues_in_code\" = find_issues_in_code,\n \"optimize_code\" = optimize_code,\n \"refactor_code\" = refactor_code,\n stop(\"`addin_name` not found.\")\n )\n # Get the selected code.\n doc_context <- getActiveDocumentContext()\n selected_code <- doc_context$selection[[1]]$text\n is_full_file <- all(nchar(selected_code) == 0)\n # If no code is selected, use the whole file.\n if (is_full_file) {\n selected_code <- doc_context$contents\n }\n selected_code <- paste0(selected_code, collapse = \"\\n\")\n # Apply the addin function.\n out <- addin_function(selected_code)\n if (as.logical(Sys.getenv(\"OPENAI_ADDIN_REPLACE\", FALSE))) {\n doc_range <- doc_context$selection[[1]]$range\n if (is_full_file) {\n doc_range <- as.document_range(c(c(0, 0), c(Inf, Inf)))\n }\n modifyRange(doc_range, out, doc_context$id)\n } else if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT output:\\n\\n\", out, \"\\n\"))\n } else {\n warning(\"Please set one of `OPENAI_ADDIN_REPLACE=TRUE` or `OPENAI_VERBOSE=TRUE`\")\n }\n invisible(NULL)\n}\n\nrun_addin_comment_code <- function() run_addin(\"comment_code\")\nrun_addin_complete_code <- function() run_addin(\"complete_code\")\nrun_addin_create_unit_tests <- function() run_addin(\"create_unit_tests\")\nrun_addin_create_variable_name <- function() run_addin(\"create_variable_name\")\nrun_addin_document_code <- function() run_addin(\"document_code\")\nrun_addin_explain_code <- function() run_addin(\"explain_code\")\nrun_addin_find_issues_in_code <- function() run_addin(\"find_issues_in_code\")\nrun_addin_optimize_code <- function() run_addin(\"optimize_code\")\nrun_addin_refactor_code <- function() run_addin(\"refactor_code\")\n\n#' Ask ChatGPT\n#'\n#' Opens an interactive chat session with ChatGPT\n#'\n#' @importFrom miniUI gadgetTitleBar miniPage\n#' @importFrom shiny actionButton br icon observeEvent onStop runGadget stopApp textAreaInput\n#' @importFrom shiny updateTextAreaInput wellPanel\n#' @importFrom utils getFromNamespace\n#'\nrun_addin_ask_chatgpt <- function() {\n reset_chat_session()\n ui <- miniPage(wellPanel(\n gadgetTitleBar(\"Ask ChatGPT\", NULL),\n textAreaInput(\"question\", \"Question:\", width = \"100%\", height = \"150px\"),\n actionButton(\"ask_button\", \"Ask\", icon(\"paper-plane\")),\n br(), br(),\n textAreaInput(\"answer\", \"Answer:\", width = \"100%\", height = \"150px\")\n ))\n server <- function(input, output, session) {\n observeEvent(input$ask_button, {\n chatgpt_reply <- ask_chatgpt(input$question)\n if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT output:\\n\\n\", chatgpt_reply, \"\\n\"))\n }\n updateTextAreaInput(session, \"answer\", value = chatgpt_reply)\n })\n observeEvent(input$done, {\n reset_chat_session()\n stopApp()\n })\n onStop(reset_chat_session)\n }\n runGadget(ui, server)\n}\n"], ["/chatgpt/R/build_prompt_content.R", "#' Build Prompt Content\n#'\n#' @param question The question to ask ChatGPT.\n#' @param images A list of images to attach to the question. It could be a list of URLs or paths.\n#'\n#' @importFrom xfun base64_encode\n#'\nbuild_prompt_content <- function(question, images) {\n if (length(images) == 0) {\n return(question)\n }\n prompt_content <- list(list(type = \"text\", text = question))\n append(prompt_content, lapply(images, function(image) {\n # If it's a local file, then transform it to base 64 encoding. If not, return the \"URL\".\n image_url <- image\n if (file.exists(image)) {\n image_url <- paste0(\"data:image/jpeg;base64,\", base64_encode(image))\n }\n list(type = \"image_url\", image_url = list(url = image_url))\n }))\n}\n"], ["/chatgpt/R/parse_response.R", "#' Parse OpenAI API Response\n#'\n#' Takes the raw response from the OpenAI API and extracts the text content from it.\n#'\n#' @param raw_responses The raw response object returned by the OpenAI API.\n#' @param verbosity The verbosity level for this function.\n#'\n#' @return Returns a character vector containing the text content of the response.\n#'\nparse_response <- function(raw_responses, verbosity = get_verbosity()) {\n # Parse the message content of the list of raw_responses. Trim those messages, and paste them.\n parsed_response <- paste(trimws(sapply(raw_responses, function(response) {\n sapply(response$choices, function(x) x$message$content)\n })), collapse = \"\")\n if (verbosity > 2) {\n # If we are in 3-verbose mode, add the raw_responses as an attribute to the return object.\n attr(parsed_response, \"raw_responses\") <- raw_responses\n }\n parsed_response\n}\n"], ["/chatgpt/R/create_unit_tests.R", "#' ChatGPT: Create Unit Tests\n#'\n#' Create `{testthat}` test cases for the code.\n#'\n#' @param code The code for which to create unit tests by ChatGPT. If not provided, it will use\n#' what's copied on the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(create_unit_tests(\"squared_numbers <- function(numbers) {\\n numbers ^ 2\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncreate_unit_tests <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0(\n \"Using testthat 3e, version over 3.0.0, create a full testthat file, with test cases for the \",\n 'following R code: \"', code, '\"'\n )\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/chatgpt-package.R", "#' 'OpenAI's 'ChatGPT' <https://chat.openai.com/> coding assistant for 'RStudio'. A set\n#' of functions and 'RStudio' addins that aim to help the R developer in tedious coding tasks.\n#'\n\"_PACKAGE\"\n\n.state <- new.env(parent = emptyenv())\n\n# Empty chat session messages at startup.\nassign(\"chat_session_messages\", list(), envir = .state)\n\napi_url <- Sys.getenv(\"OPENAI_API_URL\", \"https://api.openai.com/v1\")\n"], ["/chatgpt/R/reset_chat_session.R", "#' Reset Chat Session\n#'\n#' This function is intended to be used with `ask_chatgpt`. If we are using `ask_chatgpt` to chat with ChatGPT, and\n#' we want to start a new conversation, we must call `reset_chat_session`.\n#'\n#' @param system_role ChatGPT's role as an AI assistant.\n#' @param session_id The ID of the session to be used. If `NULL`, this function will have no effect.\n#'\n#' @export\n#'\nreset_chat_session <- function(system_role = \"You are a helpful assistant.\", session_id = \"1\") {\n if (is.null(session_id)) {\n return()\n }\n if (is.list(system_role)) {\n # If `system_role` is a list, then it is a ChatGPT session object.\n session <- system_role\n } else {\n # Otherwise, it's a string specifying ChatGPT's role.\n session <- list(list(role = \"system\", content = system_role))\n }\n all_sessions <- get(\"chat_session_messages\", envir = .state)\n all_sessions[[as.character(session_id)]] <- session\n assign(\"chat_session_messages\", all_sessions, envir = .state)\n}\n"], ["/chatgpt/R/get_chat_session.R", "#' Get Chat Session\n#'\n#' @param session_id The ID of the session to be used. If `NULL`, it will return an empty session.\n#'\nget_chat_session <- function(session_id = \"1\") {\n default_session <- list(list(role = \"system\", content = \"You are a helpful assistant.\"))\n if (is.null(session_id)) {\n return(default_session)\n }\n session <- get(\"chat_session_messages\", envir = .state)[[as.character(session_id)]]\n # If the session was not found, then it's a new (default) session.\n if (is.null(session)) {\n session <- default_session\n }\n session\n}\n"], ["/chatgpt/R/get_verbosity.R", "#' Get Verbosity Level\n#'\nget_verbosity <- function() {\n # `OPENAI_VERBOSE` should be one of `numeric` or `FALSE`/`TRUE`. But we'll return it as numeric.\n suppressWarnings(max(\n as.logical(Sys.getenv(\"OPENAI_VERBOSE\", TRUE)),\n as.numeric(Sys.getenv(\"OPENAI_VERBOSE\", TRUE)),\n na.rm = TRUE\n ))\n}\n"], ["/chatgpt/R/create_variable_name.R", "#' ChatGPT: Create Variable Name\n#'\n#' @param code The code for which to give a variable name to its result. If not provided, it will\n#' use what's copied on the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(create_variable_name(\"sapply(1:10, function(i) i ** 2)\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncreate_variable_name <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Give a good variable name to the result of the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/document_code.R", "#' ChatGPT: Document Code (in roxygen2 format)\n#'\n#' @param code The code to be documented by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(document_code(\"square_numbers <- function(numbers) numbers ** 2\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ndocument_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Document, in roxygen2 format, this R function: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/explain_code.R", "#' ChatGPT: Explain Code\n#'\n#' @param code The code to be explained by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(explain_code(\"for (i in 1:10) {\\n print(i ** 2)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nexplain_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Explain the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/comment_code.R", "#' ChatGPT: Comment Code\n#'\n#' @param code The code to be commented by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(comment_code(\"for (i in 1:10) {\\n print(i ** 2)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncomment_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Add inline comments to the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/optimize_code.R", "#' ChatGPT: Optimize Code\n#'\n#' @param code The code to be optimized by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(optimize_code(\"i <- 10\\nwhile (i > 0) {\\n i <- i - 1\\n print(i)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\noptimize_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Optimize the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/refactor_code.R", "#' ChatGPT: Refactor Code\n#'\n#' @param code The code to be refactored by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(refactor_code(\"i <- 10\\nwhile (i > 0) {\\n i <- i - 1\\n print(i)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nrefactor_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Refactor the following R code, returning valid R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/find_issues_in_code.R", "#' ChatGPT: Find Issues in Code\n#'\n#' @param code The code to be analyzed by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(find_issues_in_code(\"i <- 0\\nwhile (i < 0) {\\n i <- i - 1\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nfind_issues_in_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Find issues or bugs in the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/complete_code.R", "#' ChatGPT: Complete Code\n#'\n#' @param code The code to be completed by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(complete_code(\"# A function to square each element of a vector\\nsquare_each <- function(\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncomplete_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Complete the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:11:04", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(prompt, out_file = tempfile(fileext = \".png\"),\n openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {}", "code_description": "This code segment functions to: Send a formatted request to an external image generation API using specified parameters, handle the response validation, and retrieve the resulting output file from the service's returned data URL."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(prompt, out_file = tempfile(fileext = \".png\"),\n openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n if (missing(prompt)) stop(\"Prompt must be specified\")\n if (nchar(openai_api_key) == 0) stop(\"OPENAI_API_KEY environment variable not set\")\n \n body <- list(\n model = \"dall-e-3\",\n prompt = prompt,\n size = \"1024x1024\",\n n = 1\n )\n \n response <- POST(\n \"https://api.openai.com/v1/images/generations\",\n add_headers(\n \"Authorization\" = paste(\"Bearer\", openai_api_key),\n \"Content-Type\" = \"application/json\"\n ),\n body = toJSON(body, auto_unbox = TRUE)\n )\n \n stop_for_status(response)\n response_content <- fromJSON(content(response, \"text\", encoding = \"UTF-8\"))\n image_url <- response_content$data$url\n \n download.file(image_url, out_file, mode = \"wb\")\n invisible(out_file)\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-11-24"}, "editdistance_info": {"edit_distance": 31.4159, "calculate_time": "2025-08-21 01:11:24", "true_code_clean": "function(prompt, out_file = tempfile(fileext = \".png\"),\n openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n post_res <- POST(\n paste0(api_url, \"/images/generations\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = toJSON(\n list(model = \"dall-e-3\", prompt = prompt, n = 1, size = \"1024x1024\"),\n auto_unbox = TRUE\n )\n )\n stop_for_status(post_res)\n download.file(fromJSON(content(post_res, as = \"text\", encoding = \"UTF-8\"))$data$url, out_file)\n return(out_file)\n}", "predict_code_clean": "function(prompt, out_file = tempfile(fileext = \".png\"),\n openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n if (missing(prompt)) stop(\"Prompt must be specified\")\n if (nchar(openai_api_key) == 0) stop(\"OPENAI_API_KEY environment variable not set\")\n body <- list(\n model = \"dall-e-3\",\n prompt = prompt,\n size = \"1024x1024\",\n n = 1\n )\n response <- POST(\n \"https://api.openai.com/v1/images/generations\",\n add_headers(\n \"Authorization\" = paste(\"Bearer\", openai_api_key),\n \"Content-Type\" = \"application/json\"\n ),\n body = toJSON(body, auto_unbox = TRUE)\n )\n stop_for_status(response)\n response_content <- fromJSON(content(response, \"text\", encoding = \"UTF-8\"))\n image_url <- response_content$data$url\n download.file(image_url, out_file, mode = \"wb\")\n invisible(out_file)\n}"}}
{"repo_name": "chatgpt", "file_name": "/chatgpt/R/get_chat_session.R", "inference_info": {"prefix_code": "#' Get Chat Session\n#'\n#' @param session_id The ID of the session to be used. If `NULL`, it will return an empty session.\n#'\nget_chat_session <- ", "suffix_code": "\n", "middle_code": "function(session_id = \"1\") {\n default_session <- list(list(role = \"system\", content = \"You are a helpful assistant.\"))\n if (is.null(session_id)) {\n return(default_session)\n }\n session <- get(\"chat_session_messages\", envir = .state)[[as.character(session_id)]]\n if (is.null(session)) {\n session <- default_session\n }\n session\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/chatgpt/R/reset_chat_session.R", "#' Reset Chat Session\n#'\n#' This function is intended to be used with `ask_chatgpt`. If we are using `ask_chatgpt` to chat with ChatGPT, and\n#' we want to start a new conversation, we must call `reset_chat_session`.\n#'\n#' @param system_role ChatGPT's role as an AI assistant.\n#' @param session_id The ID of the session to be used. If `NULL`, this function will have no effect.\n#'\n#' @export\n#'\nreset_chat_session <- function(system_role = \"You are a helpful assistant.\", session_id = \"1\") {\n if (is.null(session_id)) {\n return()\n }\n if (is.list(system_role)) {\n # If `system_role` is a list, then it is a ChatGPT session object.\n session <- system_role\n } else {\n # Otherwise, it's a string specifying ChatGPT's role.\n session <- list(list(role = \"system\", content = system_role))\n }\n all_sessions <- get(\"chat_session_messages\", envir = .state)\n all_sessions[[as.character(session_id)]] <- session\n assign(\"chat_session_messages\", all_sessions, envir = .state)\n}\n"], ["/chatgpt/R/ask_chatgpt.R", "#' Ask ChatGPT\n#'\n#' Note: See also `reset_chat_session`.\n#'\n#' @param question The question to ask ChatGPT.\n#' @param session_id The ID of the session to be used. We can have different conversations by using\n#' different session IDs.\n#' @param openai_api_key OpenAI's API key.\n#' @param images A list of images to attach to the question. It could be a list of URLs or paths.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(ask_chatgpt(\"What do you think about R language?\"))\n#' }\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nask_chatgpt <- function(question, session_id = \"1\", openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"),\n images = NULL) {\n # Get the existing chat session messages, and add the new message.\n chat_session_messages <- append(get_chat_session(session_id), list(\n list(role = \"user\", content = build_prompt_content(question, images))\n ))\n # Send the query to ChatGPT.\n chat_gpt_reply <- parse_response(\n gpt_get_completions(question, openai_api_key, chat_session_messages)\n )\n chat_session_messages <- append(chat_session_messages, list(\n list(role = \"assistant\", content = chat_gpt_reply)\n ))\n # Update the chat session messages with the new question and the reply.\n reset_chat_session(chat_session_messages, session_id)\n chat_gpt_reply\n}\n"], ["/chatgpt/R/addins.R", "#' Run a ChatGPT RStudio Addin\n#'\n#' @param addin_name The name of the adding to execute.\n#'\n#' @importFrom rstudioapi as.document_range getActiveDocumentContext modifyRange\n#'\nrun_addin <- function(addin_name) {\n # Select which addin has to be used.\n addin_function <- switch(addin_name,\n \"comment_code\" = comment_code,\n \"complete_code\" = complete_code,\n \"create_unit_tests\" = create_unit_tests,\n \"create_variable_name\" = create_variable_name,\n \"document_code\" = document_code,\n \"explain_code\" = explain_code,\n \"find_issues_in_code\" = find_issues_in_code,\n \"optimize_code\" = optimize_code,\n \"refactor_code\" = refactor_code,\n stop(\"`addin_name` not found.\")\n )\n # Get the selected code.\n doc_context <- getActiveDocumentContext()\n selected_code <- doc_context$selection[[1]]$text\n is_full_file <- all(nchar(selected_code) == 0)\n # If no code is selected, use the whole file.\n if (is_full_file) {\n selected_code <- doc_context$contents\n }\n selected_code <- paste0(selected_code, collapse = \"\\n\")\n # Apply the addin function.\n out <- addin_function(selected_code)\n if (as.logical(Sys.getenv(\"OPENAI_ADDIN_REPLACE\", FALSE))) {\n doc_range <- doc_context$selection[[1]]$range\n if (is_full_file) {\n doc_range <- as.document_range(c(c(0, 0), c(Inf, Inf)))\n }\n modifyRange(doc_range, out, doc_context$id)\n } else if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT output:\\n\\n\", out, \"\\n\"))\n } else {\n warning(\"Please set one of `OPENAI_ADDIN_REPLACE=TRUE` or `OPENAI_VERBOSE=TRUE`\")\n }\n invisible(NULL)\n}\n\nrun_addin_comment_code <- function() run_addin(\"comment_code\")\nrun_addin_complete_code <- function() run_addin(\"complete_code\")\nrun_addin_create_unit_tests <- function() run_addin(\"create_unit_tests\")\nrun_addin_create_variable_name <- function() run_addin(\"create_variable_name\")\nrun_addin_document_code <- function() run_addin(\"document_code\")\nrun_addin_explain_code <- function() run_addin(\"explain_code\")\nrun_addin_find_issues_in_code <- function() run_addin(\"find_issues_in_code\")\nrun_addin_optimize_code <- function() run_addin(\"optimize_code\")\nrun_addin_refactor_code <- function() run_addin(\"refactor_code\")\n\n#' Ask ChatGPT\n#'\n#' Opens an interactive chat session with ChatGPT\n#'\n#' @importFrom miniUI gadgetTitleBar miniPage\n#' @importFrom shiny actionButton br icon observeEvent onStop runGadget stopApp textAreaInput\n#' @importFrom shiny updateTextAreaInput wellPanel\n#' @importFrom utils getFromNamespace\n#'\nrun_addin_ask_chatgpt <- function() {\n reset_chat_session()\n ui <- miniPage(wellPanel(\n gadgetTitleBar(\"Ask ChatGPT\", NULL),\n textAreaInput(\"question\", \"Question:\", width = \"100%\", height = \"150px\"),\n actionButton(\"ask_button\", \"Ask\", icon(\"paper-plane\")),\n br(), br(),\n textAreaInput(\"answer\", \"Answer:\", width = \"100%\", height = \"150px\")\n ))\n server <- function(input, output, session) {\n observeEvent(input$ask_button, {\n chatgpt_reply <- ask_chatgpt(input$question)\n if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT output:\\n\\n\", chatgpt_reply, \"\\n\"))\n }\n updateTextAreaInput(session, \"answer\", value = chatgpt_reply)\n })\n observeEvent(input$done, {\n reset_chat_session()\n stopApp()\n })\n onStop(reset_chat_session)\n }\n runGadget(ui, server)\n}\n"], ["/chatgpt/R/gpt_get_completions.R", "#' Get GPT Completions Endpoint\n#'\n#' @param prompt The prompt to generate completions for.\n#' @param openai_api_key OpenAI's API key.\n#' @param messages Available variable, to send the needed messages list to ChatGPT.\n#'\n#' @importFrom httr add_headers content content_type_json POST use_proxy\n#' @importFrom jsonlite toJSON\n#'\ngpt_get_completions <- function(prompt, openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"),\n messages = NULL) {\n if (nchar(openai_api_key) == 0) {\n stop(\"`OPENAI_API_KEY` not provided.\")\n }\n # See https://platform.openai.com/docs/api-reference/chat .\n params <- list(\n model = Sys.getenv(\"OPENAI_MODEL\", \"gpt-4o-mini\"),\n max_tokens = as.numeric(Sys.getenv(\"OPENAI_MAX_TOKENS\", 256)),\n temperature = as.numeric(Sys.getenv(\"OPENAI_TEMPERATURE\", 1)),\n top_p = as.numeric(Sys.getenv(\"OPENAI_TOP_P\", 1)),\n frequency_penalty = as.numeric(Sys.getenv(\"OPENAI_FREQUENCY_PENALTY\", 0)),\n presence_penalty = as.numeric(Sys.getenv(\"OPENAI_PRESENCE_PENALTY\", 0)),\n logprobs = as.logical(Sys.getenv(\"OPENAI_LOGPROBS\", FALSE))\n )\n if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT input:\\n\\n\", prompt, \"\\n\"))\n }\n return_language <- Sys.getenv(\"OPENAI_RETURN_LANGUAGE\")\n if (nchar(return_language) > 0) {\n return_language <- paste0(\"You return all your replies in \", return_language, \".\")\n }\n if (is.null(messages)) {\n messages <- list(\n list(\n role = \"system\",\n content = paste(\n \"You are a helpful assistant with extensive knowledge of R programming.\",\n return_language\n )\n ),\n list(role = \"user\", content = prompt)\n )\n } else {\n # If there are messages provided, then add the `return_language` if available.\n messages[[which(sapply(messages, function(message) message$role == \"system\"))]]$content <-\n paste(\n messages[[which(sapply(messages, function(message) message$role == \"system\"))]]$content,\n return_language\n )\n }\n # Get the proxy to use, if provided.\n proxy <- NULL\n if (nchar(Sys.getenv(\"OPENAI_PROXY\")) > 0) {\n proxy <- Sys.getenv(\"OPENAI_PROXY\")\n if (grepl(\"^(?:\\\\d{1,3}\\\\.){3}\\\\d{1,3}:\\\\d{2,5}$\", proxy)) {\n proxy <- use_proxy(gsub(\":.*\", \"\", proxy), as.numeric(gsub(\".*:\", \"\", proxy)))\n } else {\n stop(\"Invalid proxy provided in `OPENAI_PROXY`: \", proxy)\n }\n }\n # Run the API query.\n final_res <- list()\n keep_querying <- TRUE\n while (keep_querying) {\n post_res <- POST(\n paste0(api_url, \"/chat/completions\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = toJSON(c(params, list(messages = messages)), auto_unbox = TRUE),\n proxy\n )\n if (!post_res$status_code %in% 200:299) {\n stop(content(post_res))\n }\n if (get_verbosity() > 1) {\n # If verbose is over 1, show the ongoing GPT response.\n message(content(post_res, as = \"text\", encoding = \"UTF-8\"))\n }\n post_res <- content(post_res)\n final_res <- append(final_res, list(post_res))\n # In the case the finish_reason is the length of the message, then we need to keep querying.\n keep_querying <- all(sapply(post_res$choices, function(x) x$finish_reason == \"length\"))\n # And update the messages sent to ChatGPT, in order to continue the current session.\n messages <- append(\n append(\n messages,\n list(list(role = \"assistant\", content = parse_response(list(post_res), verbosity = 0)))\n ),\n list(list(role = \"user\", content = \"continue\"))\n )\n }\n final_res\n}\n"], ["/chatgpt/R/chatgpt-package.R", "#' 'OpenAI's 'ChatGPT' <https://chat.openai.com/> coding assistant for 'RStudio'. A set\n#' of functions and 'RStudio' addins that aim to help the R developer in tedious coding tasks.\n#'\n\"_PACKAGE\"\n\n.state <- new.env(parent = emptyenv())\n\n# Empty chat session messages at startup.\nassign(\"chat_session_messages\", list(), envir = .state)\n\napi_url <- Sys.getenv(\"OPENAI_API_URL\", \"https://api.openai.com/v1\")\n"], ["/chatgpt/R/build_prompt_content.R", "#' Build Prompt Content\n#'\n#' @param question The question to ask ChatGPT.\n#' @param images A list of images to attach to the question. It could be a list of URLs or paths.\n#'\n#' @importFrom xfun base64_encode\n#'\nbuild_prompt_content <- function(question, images) {\n if (length(images) == 0) {\n return(question)\n }\n prompt_content <- list(list(type = \"text\", text = question))\n append(prompt_content, lapply(images, function(image) {\n # If it's a local file, then transform it to base 64 encoding. If not, return the \"URL\".\n image_url <- image\n if (file.exists(image)) {\n image_url <- paste0(\"data:image/jpeg;base64,\", base64_encode(image))\n }\n list(type = \"image_url\", image_url = list(url = image_url))\n }))\n}\n"], ["/chatgpt/R/parse_response.R", "#' Parse OpenAI API Response\n#'\n#' Takes the raw response from the OpenAI API and extracts the text content from it.\n#'\n#' @param raw_responses The raw response object returned by the OpenAI API.\n#' @param verbosity The verbosity level for this function.\n#'\n#' @return Returns a character vector containing the text content of the response.\n#'\nparse_response <- function(raw_responses, verbosity = get_verbosity()) {\n # Parse the message content of the list of raw_responses. Trim those messages, and paste them.\n parsed_response <- paste(trimws(sapply(raw_responses, function(response) {\n sapply(response$choices, function(x) x$message$content)\n })), collapse = \"\")\n if (verbosity > 2) {\n # If we are in 3-verbose mode, add the raw_responses as an attribute to the return object.\n attr(parsed_response, \"raw_responses\") <- raw_responses\n }\n parsed_response\n}\n"], ["/chatgpt/R/generate_image.R", "#' Generate an Image With DALL-E 3\n#'\n#' @param prompt The prompt for image generation.\n#' @param out_file The path where to save the generated image.\n#' @param openai_api_key OpenAI's API key.\n#'\n#' @importFrom httr add_headers content content_type_json POST stop_for_status\n#' @importFrom jsonlite fromJSON toJSON\n#' @importFrom utils download.file\n#'\n#' @export\n#'\ngenerate_image <- function(prompt, out_file = tempfile(fileext = \".png\"),\n openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n post_res <- POST(\n paste0(api_url, \"/images/generations\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = toJSON(\n list(model = \"dall-e-3\", prompt = prompt, n = 1, size = \"1024x1024\"),\n auto_unbox = TRUE\n )\n )\n stop_for_status(post_res)\n download.file(fromJSON(content(post_res, as = \"text\", encoding = \"UTF-8\"))$data$url, out_file)\n return(out_file)\n}\n"], ["/chatgpt/R/get_verbosity.R", "#' Get Verbosity Level\n#'\nget_verbosity <- function() {\n # `OPENAI_VERBOSE` should be one of `numeric` or `FALSE`/`TRUE`. But we'll return it as numeric.\n suppressWarnings(max(\n as.logical(Sys.getenv(\"OPENAI_VERBOSE\", TRUE)),\n as.numeric(Sys.getenv(\"OPENAI_VERBOSE\", TRUE)),\n na.rm = TRUE\n ))\n}\n"], ["/chatgpt/R/list_models.R", "#' ChatGPT: List Models\n#'\n#' @param openai_api_key OpenAI's API key.\n#'\n#' @examples\n#' \\dontrun{\n#' list_models()\n#' }\n#'\n#' @importFrom httr add_headers content GET stop_for_status\n#' @importFrom jsonlite fromJSON\n#'\n#' @return A data.frame with the available models to be used by OpenAI's API.\n#'\n#' @export\n#'\nlist_models <- function(openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n get_res <- GET(\n paste0(api_url, \"/models\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key))\n )\n stop_for_status(get_res)\n fromJSON(content(get_res, as = \"text\", encoding = \"UTF-8\"))$data\n}\n"], ["/chatgpt/R/create_unit_tests.R", "#' ChatGPT: Create Unit Tests\n#'\n#' Create `{testthat}` test cases for the code.\n#'\n#' @param code The code for which to create unit tests by ChatGPT. If not provided, it will use\n#' what's copied on the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(create_unit_tests(\"squared_numbers <- function(numbers) {\\n numbers ^ 2\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncreate_unit_tests <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0(\n \"Using testthat 3e, version over 3.0.0, create a full testthat file, with test cases for the \",\n 'following R code: \"', code, '\"'\n )\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/document_code.R", "#' ChatGPT: Document Code (in roxygen2 format)\n#'\n#' @param code The code to be documented by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(document_code(\"square_numbers <- function(numbers) numbers ** 2\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ndocument_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Document, in roxygen2 format, this R function: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/comment_code.R", "#' ChatGPT: Comment Code\n#'\n#' @param code The code to be commented by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(comment_code(\"for (i in 1:10) {\\n print(i ** 2)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncomment_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Add inline comments to the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/create_variable_name.R", "#' ChatGPT: Create Variable Name\n#'\n#' @param code The code for which to give a variable name to its result. If not provided, it will\n#' use what's copied on the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(create_variable_name(\"sapply(1:10, function(i) i ** 2)\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncreate_variable_name <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Give a good variable name to the result of the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/explain_code.R", "#' ChatGPT: Explain Code\n#'\n#' @param code The code to be explained by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(explain_code(\"for (i in 1:10) {\\n print(i ** 2)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nexplain_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Explain the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/optimize_code.R", "#' ChatGPT: Optimize Code\n#'\n#' @param code The code to be optimized by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(optimize_code(\"i <- 10\\nwhile (i > 0) {\\n i <- i - 1\\n print(i)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\noptimize_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Optimize the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/refactor_code.R", "#' ChatGPT: Refactor Code\n#'\n#' @param code The code to be refactored by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(refactor_code(\"i <- 10\\nwhile (i > 0) {\\n i <- i - 1\\n print(i)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nrefactor_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Refactor the following R code, returning valid R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/find_issues_in_code.R", "#' ChatGPT: Find Issues in Code\n#'\n#' @param code The code to be analyzed by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(find_issues_in_code(\"i <- 0\\nwhile (i < 0) {\\n i <- i - 1\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nfind_issues_in_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Find issues or bugs in the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/complete_code.R", "#' ChatGPT: Complete Code\n#'\n#' @param code The code to be completed by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(complete_code(\"# A function to square each element of a vector\\nsquare_each <- function(\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncomplete_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Complete the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:11:04", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(session_id = \"1\") {}", "code_description": "This code segment functions to: Retrieve stored conversation context based on an identifier value, provide default system interaction parameters when invalid references are detected, and maintain baseline communication settings for subsequent dialogue processing."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(session_id = \"1\") {\n if (is.null(session_id)) {\n return(list())\n }\n # In a real implementation, this would retrieve session from storage\n list(id = session_id, messages = list())\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-11-29"}, "editdistance_info": {"edit_distance": 24.1379, "calculate_time": "2025-08-21 01:11:29", "true_code_clean": "function(session_id = \"1\") {\n default_session <- list(list(role = \"system\", content = \"You are a helpful assistant.\"))\n if (is.null(session_id)) {\n return(default_session)\n }\n session <- get(\"chat_session_messages\", envir = .state)[[as.character(session_id)]]\n if (is.null(session)) {\n session <- default_session\n }\n session\n}", "predict_code_clean": "function(session_id = \"1\") {\n if (is.null(session_id)) {\n return(list())\n }\n list(id = session_id, messages = list())\n}"}}
{"repo_name": "chatgpt", "file_name": "/chatgpt/R/get_chat_session.R", "inference_info": {"prefix_code": "#' Get Chat Session\n#'\n#' @param session_id The ID of the session to be used. If `NULL`, it will return an empty session.\n#'\nget_chat_session <- ", "suffix_code": "\n", "middle_code": "function(session_id = \"1\") {\n default_session <- list(list(role = \"system\", content = \"You are a helpful assistant.\"))\n if (is.null(session_id)) {\n return(default_session)\n }\n session <- get(\"chat_session_messages\", envir = .state)[[as.character(session_id)]]\n if (is.null(session)) {\n session <- default_session\n }\n session\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/chatgpt/R/reset_chat_session.R", "#' Reset Chat Session\n#'\n#' This function is intended to be used with `ask_chatgpt`. If we are using `ask_chatgpt` to chat with ChatGPT, and\n#' we want to start a new conversation, we must call `reset_chat_session`.\n#'\n#' @param system_role ChatGPT's role as an AI assistant.\n#' @param session_id The ID of the session to be used. If `NULL`, this function will have no effect.\n#'\n#' @export\n#'\nreset_chat_session <- function(system_role = \"You are a helpful assistant.\", session_id = \"1\") {\n if (is.null(session_id)) {\n return()\n }\n if (is.list(system_role)) {\n # If `system_role` is a list, then it is a ChatGPT session object.\n session <- system_role\n } else {\n # Otherwise, it's a string specifying ChatGPT's role.\n session <- list(list(role = \"system\", content = system_role))\n }\n all_sessions <- get(\"chat_session_messages\", envir = .state)\n all_sessions[[as.character(session_id)]] <- session\n assign(\"chat_session_messages\", all_sessions, envir = .state)\n}\n"], ["/chatgpt/R/ask_chatgpt.R", "#' Ask ChatGPT\n#'\n#' Note: See also `reset_chat_session`.\n#'\n#' @param question The question to ask ChatGPT.\n#' @param session_id The ID of the session to be used. We can have different conversations by using\n#' different session IDs.\n#' @param openai_api_key OpenAI's API key.\n#' @param images A list of images to attach to the question. It could be a list of URLs or paths.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(ask_chatgpt(\"What do you think about R language?\"))\n#' }\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nask_chatgpt <- function(question, session_id = \"1\", openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"),\n images = NULL) {\n # Get the existing chat session messages, and add the new message.\n chat_session_messages <- append(get_chat_session(session_id), list(\n list(role = \"user\", content = build_prompt_content(question, images))\n ))\n # Send the query to ChatGPT.\n chat_gpt_reply <- parse_response(\n gpt_get_completions(question, openai_api_key, chat_session_messages)\n )\n chat_session_messages <- append(chat_session_messages, list(\n list(role = \"assistant\", content = chat_gpt_reply)\n ))\n # Update the chat session messages with the new question and the reply.\n reset_chat_session(chat_session_messages, session_id)\n chat_gpt_reply\n}\n"], ["/chatgpt/R/addins.R", "#' Run a ChatGPT RStudio Addin\n#'\n#' @param addin_name The name of the adding to execute.\n#'\n#' @importFrom rstudioapi as.document_range getActiveDocumentContext modifyRange\n#'\nrun_addin <- function(addin_name) {\n # Select which addin has to be used.\n addin_function <- switch(addin_name,\n \"comment_code\" = comment_code,\n \"complete_code\" = complete_code,\n \"create_unit_tests\" = create_unit_tests,\n \"create_variable_name\" = create_variable_name,\n \"document_code\" = document_code,\n \"explain_code\" = explain_code,\n \"find_issues_in_code\" = find_issues_in_code,\n \"optimize_code\" = optimize_code,\n \"refactor_code\" = refactor_code,\n stop(\"`addin_name` not found.\")\n )\n # Get the selected code.\n doc_context <- getActiveDocumentContext()\n selected_code <- doc_context$selection[[1]]$text\n is_full_file <- all(nchar(selected_code) == 0)\n # If no code is selected, use the whole file.\n if (is_full_file) {\n selected_code <- doc_context$contents\n }\n selected_code <- paste0(selected_code, collapse = \"\\n\")\n # Apply the addin function.\n out <- addin_function(selected_code)\n if (as.logical(Sys.getenv(\"OPENAI_ADDIN_REPLACE\", FALSE))) {\n doc_range <- doc_context$selection[[1]]$range\n if (is_full_file) {\n doc_range <- as.document_range(c(c(0, 0), c(Inf, Inf)))\n }\n modifyRange(doc_range, out, doc_context$id)\n } else if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT output:\\n\\n\", out, \"\\n\"))\n } else {\n warning(\"Please set one of `OPENAI_ADDIN_REPLACE=TRUE` or `OPENAI_VERBOSE=TRUE`\")\n }\n invisible(NULL)\n}\n\nrun_addin_comment_code <- function() run_addin(\"comment_code\")\nrun_addin_complete_code <- function() run_addin(\"complete_code\")\nrun_addin_create_unit_tests <- function() run_addin(\"create_unit_tests\")\nrun_addin_create_variable_name <- function() run_addin(\"create_variable_name\")\nrun_addin_document_code <- function() run_addin(\"document_code\")\nrun_addin_explain_code <- function() run_addin(\"explain_code\")\nrun_addin_find_issues_in_code <- function() run_addin(\"find_issues_in_code\")\nrun_addin_optimize_code <- function() run_addin(\"optimize_code\")\nrun_addin_refactor_code <- function() run_addin(\"refactor_code\")\n\n#' Ask ChatGPT\n#'\n#' Opens an interactive chat session with ChatGPT\n#'\n#' @importFrom miniUI gadgetTitleBar miniPage\n#' @importFrom shiny actionButton br icon observeEvent onStop runGadget stopApp textAreaInput\n#' @importFrom shiny updateTextAreaInput wellPanel\n#' @importFrom utils getFromNamespace\n#'\nrun_addin_ask_chatgpt <- function() {\n reset_chat_session()\n ui <- miniPage(wellPanel(\n gadgetTitleBar(\"Ask ChatGPT\", NULL),\n textAreaInput(\"question\", \"Question:\", width = \"100%\", height = \"150px\"),\n actionButton(\"ask_button\", \"Ask\", icon(\"paper-plane\")),\n br(), br(),\n textAreaInput(\"answer\", \"Answer:\", width = \"100%\", height = \"150px\")\n ))\n server <- function(input, output, session) {\n observeEvent(input$ask_button, {\n chatgpt_reply <- ask_chatgpt(input$question)\n if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT output:\\n\\n\", chatgpt_reply, \"\\n\"))\n }\n updateTextAreaInput(session, \"answer\", value = chatgpt_reply)\n })\n observeEvent(input$done, {\n reset_chat_session()\n stopApp()\n })\n onStop(reset_chat_session)\n }\n runGadget(ui, server)\n}\n"], ["/chatgpt/R/gpt_get_completions.R", "#' Get GPT Completions Endpoint\n#'\n#' @param prompt The prompt to generate completions for.\n#' @param openai_api_key OpenAI's API key.\n#' @param messages Available variable, to send the needed messages list to ChatGPT.\n#'\n#' @importFrom httr add_headers content content_type_json POST use_proxy\n#' @importFrom jsonlite toJSON\n#'\ngpt_get_completions <- function(prompt, openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"),\n messages = NULL) {\n if (nchar(openai_api_key) == 0) {\n stop(\"`OPENAI_API_KEY` not provided.\")\n }\n # See https://platform.openai.com/docs/api-reference/chat .\n params <- list(\n model = Sys.getenv(\"OPENAI_MODEL\", \"gpt-4o-mini\"),\n max_tokens = as.numeric(Sys.getenv(\"OPENAI_MAX_TOKENS\", 256)),\n temperature = as.numeric(Sys.getenv(\"OPENAI_TEMPERATURE\", 1)),\n top_p = as.numeric(Sys.getenv(\"OPENAI_TOP_P\", 1)),\n frequency_penalty = as.numeric(Sys.getenv(\"OPENAI_FREQUENCY_PENALTY\", 0)),\n presence_penalty = as.numeric(Sys.getenv(\"OPENAI_PRESENCE_PENALTY\", 0)),\n logprobs = as.logical(Sys.getenv(\"OPENAI_LOGPROBS\", FALSE))\n )\n if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT input:\\n\\n\", prompt, \"\\n\"))\n }\n return_language <- Sys.getenv(\"OPENAI_RETURN_LANGUAGE\")\n if (nchar(return_language) > 0) {\n return_language <- paste0(\"You return all your replies in \", return_language, \".\")\n }\n if (is.null(messages)) {\n messages <- list(\n list(\n role = \"system\",\n content = paste(\n \"You are a helpful assistant with extensive knowledge of R programming.\",\n return_language\n )\n ),\n list(role = \"user\", content = prompt)\n )\n } else {\n # If there are messages provided, then add the `return_language` if available.\n messages[[which(sapply(messages, function(message) message$role == \"system\"))]]$content <-\n paste(\n messages[[which(sapply(messages, function(message) message$role == \"system\"))]]$content,\n return_language\n )\n }\n # Get the proxy to use, if provided.\n proxy <- NULL\n if (nchar(Sys.getenv(\"OPENAI_PROXY\")) > 0) {\n proxy <- Sys.getenv(\"OPENAI_PROXY\")\n if (grepl(\"^(?:\\\\d{1,3}\\\\.){3}\\\\d{1,3}:\\\\d{2,5}$\", proxy)) {\n proxy <- use_proxy(gsub(\":.*\", \"\", proxy), as.numeric(gsub(\".*:\", \"\", proxy)))\n } else {\n stop(\"Invalid proxy provided in `OPENAI_PROXY`: \", proxy)\n }\n }\n # Run the API query.\n final_res <- list()\n keep_querying <- TRUE\n while (keep_querying) {\n post_res <- POST(\n paste0(api_url, \"/chat/completions\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = toJSON(c(params, list(messages = messages)), auto_unbox = TRUE),\n proxy\n )\n if (!post_res$status_code %in% 200:299) {\n stop(content(post_res))\n }\n if (get_verbosity() > 1) {\n # If verbose is over 1, show the ongoing GPT response.\n message(content(post_res, as = \"text\", encoding = \"UTF-8\"))\n }\n post_res <- content(post_res)\n final_res <- append(final_res, list(post_res))\n # In the case the finish_reason is the length of the message, then we need to keep querying.\n keep_querying <- all(sapply(post_res$choices, function(x) x$finish_reason == \"length\"))\n # And update the messages sent to ChatGPT, in order to continue the current session.\n messages <- append(\n append(\n messages,\n list(list(role = \"assistant\", content = parse_response(list(post_res), verbosity = 0)))\n ),\n list(list(role = \"user\", content = \"continue\"))\n )\n }\n final_res\n}\n"], ["/chatgpt/R/chatgpt-package.R", "#' 'OpenAI's 'ChatGPT' <https://chat.openai.com/> coding assistant for 'RStudio'. A set\n#' of functions and 'RStudio' addins that aim to help the R developer in tedious coding tasks.\n#'\n\"_PACKAGE\"\n\n.state <- new.env(parent = emptyenv())\n\n# Empty chat session messages at startup.\nassign(\"chat_session_messages\", list(), envir = .state)\n\napi_url <- Sys.getenv(\"OPENAI_API_URL\", \"https://api.openai.com/v1\")\n"], ["/chatgpt/R/build_prompt_content.R", "#' Build Prompt Content\n#'\n#' @param question The question to ask ChatGPT.\n#' @param images A list of images to attach to the question. It could be a list of URLs or paths.\n#'\n#' @importFrom xfun base64_encode\n#'\nbuild_prompt_content <- function(question, images) {\n if (length(images) == 0) {\n return(question)\n }\n prompt_content <- list(list(type = \"text\", text = question))\n append(prompt_content, lapply(images, function(image) {\n # If it's a local file, then transform it to base 64 encoding. If not, return the \"URL\".\n image_url <- image\n if (file.exists(image)) {\n image_url <- paste0(\"data:image/jpeg;base64,\", base64_encode(image))\n }\n list(type = \"image_url\", image_url = list(url = image_url))\n }))\n}\n"], ["/chatgpt/R/parse_response.R", "#' Parse OpenAI API Response\n#'\n#' Takes the raw response from the OpenAI API and extracts the text content from it.\n#'\n#' @param raw_responses The raw response object returned by the OpenAI API.\n#' @param verbosity The verbosity level for this function.\n#'\n#' @return Returns a character vector containing the text content of the response.\n#'\nparse_response <- function(raw_responses, verbosity = get_verbosity()) {\n # Parse the message content of the list of raw_responses. Trim those messages, and paste them.\n parsed_response <- paste(trimws(sapply(raw_responses, function(response) {\n sapply(response$choices, function(x) x$message$content)\n })), collapse = \"\")\n if (verbosity > 2) {\n # If we are in 3-verbose mode, add the raw_responses as an attribute to the return object.\n attr(parsed_response, \"raw_responses\") <- raw_responses\n }\n parsed_response\n}\n"], ["/chatgpt/R/generate_image.R", "#' Generate an Image With DALL-E 3\n#'\n#' @param prompt The prompt for image generation.\n#' @param out_file The path where to save the generated image.\n#' @param openai_api_key OpenAI's API key.\n#'\n#' @importFrom httr add_headers content content_type_json POST stop_for_status\n#' @importFrom jsonlite fromJSON toJSON\n#' @importFrom utils download.file\n#'\n#' @export\n#'\ngenerate_image <- function(prompt, out_file = tempfile(fileext = \".png\"),\n openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n post_res <- POST(\n paste0(api_url, \"/images/generations\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = toJSON(\n list(model = \"dall-e-3\", prompt = prompt, n = 1, size = \"1024x1024\"),\n auto_unbox = TRUE\n )\n )\n stop_for_status(post_res)\n download.file(fromJSON(content(post_res, as = \"text\", encoding = \"UTF-8\"))$data$url, out_file)\n return(out_file)\n}\n"], ["/chatgpt/R/get_verbosity.R", "#' Get Verbosity Level\n#'\nget_verbosity <- function() {\n # `OPENAI_VERBOSE` should be one of `numeric` or `FALSE`/`TRUE`. But we'll return it as numeric.\n suppressWarnings(max(\n as.logical(Sys.getenv(\"OPENAI_VERBOSE\", TRUE)),\n as.numeric(Sys.getenv(\"OPENAI_VERBOSE\", TRUE)),\n na.rm = TRUE\n ))\n}\n"], ["/chatgpt/R/list_models.R", "#' ChatGPT: List Models\n#'\n#' @param openai_api_key OpenAI's API key.\n#'\n#' @examples\n#' \\dontrun{\n#' list_models()\n#' }\n#'\n#' @importFrom httr add_headers content GET stop_for_status\n#' @importFrom jsonlite fromJSON\n#'\n#' @return A data.frame with the available models to be used by OpenAI's API.\n#'\n#' @export\n#'\nlist_models <- function(openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n get_res <- GET(\n paste0(api_url, \"/models\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key))\n )\n stop_for_status(get_res)\n fromJSON(content(get_res, as = \"text\", encoding = \"UTF-8\"))$data\n}\n"], ["/chatgpt/R/create_unit_tests.R", "#' ChatGPT: Create Unit Tests\n#'\n#' Create `{testthat}` test cases for the code.\n#'\n#' @param code The code for which to create unit tests by ChatGPT. If not provided, it will use\n#' what's copied on the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(create_unit_tests(\"squared_numbers <- function(numbers) {\\n numbers ^ 2\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncreate_unit_tests <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0(\n \"Using testthat 3e, version over 3.0.0, create a full testthat file, with test cases for the \",\n 'following R code: \"', code, '\"'\n )\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/document_code.R", "#' ChatGPT: Document Code (in roxygen2 format)\n#'\n#' @param code The code to be documented by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(document_code(\"square_numbers <- function(numbers) numbers ** 2\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ndocument_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Document, in roxygen2 format, this R function: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/comment_code.R", "#' ChatGPT: Comment Code\n#'\n#' @param code The code to be commented by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(comment_code(\"for (i in 1:10) {\\n print(i ** 2)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncomment_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Add inline comments to the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/create_variable_name.R", "#' ChatGPT: Create Variable Name\n#'\n#' @param code The code for which to give a variable name to its result. If not provided, it will\n#' use what's copied on the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(create_variable_name(\"sapply(1:10, function(i) i ** 2)\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncreate_variable_name <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Give a good variable name to the result of the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/explain_code.R", "#' ChatGPT: Explain Code\n#'\n#' @param code The code to be explained by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(explain_code(\"for (i in 1:10) {\\n print(i ** 2)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nexplain_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Explain the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/optimize_code.R", "#' ChatGPT: Optimize Code\n#'\n#' @param code The code to be optimized by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(optimize_code(\"i <- 10\\nwhile (i > 0) {\\n i <- i - 1\\n print(i)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\noptimize_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Optimize the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/refactor_code.R", "#' ChatGPT: Refactor Code\n#'\n#' @param code The code to be refactored by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(refactor_code(\"i <- 10\\nwhile (i > 0) {\\n i <- i - 1\\n print(i)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nrefactor_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Refactor the following R code, returning valid R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/find_issues_in_code.R", "#' ChatGPT: Find Issues in Code\n#'\n#' @param code The code to be analyzed by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(find_issues_in_code(\"i <- 0\\nwhile (i < 0) {\\n i <- i - 1\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nfind_issues_in_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Find issues or bugs in the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/complete_code.R", "#' ChatGPT: Complete Code\n#'\n#' @param code The code to be completed by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(complete_code(\"# A function to square each element of a vector\\nsquare_each <- function(\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncomplete_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Complete the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:11:04", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(session_id = \"1\") {}", "code_description": "This code segment functions to: Retrieve stored conversation context based on an identifier value, returning a predefined default configuration when no valid identifier is provided or when no matching context exists in persistent storage."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(session_id = NULL) {\n if (is.null(session_id)) {\n return(list())\n }\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-11-29"}, "editdistance_info": {"edit_distance": 19.5402, "calculate_time": "2025-08-21 01:11:29", "true_code_clean": "function(session_id = \"1\") {\n default_session <- list(list(role = \"system\", content = \"You are a helpful assistant.\"))\n if (is.null(session_id)) {\n return(default_session)\n }\n session <- get(\"chat_session_messages\", envir = .state)[[as.character(session_id)]]\n if (is.null(session)) {\n session <- default_session\n }\n session\n}", "predict_code_clean": "function(session_id = NULL) {\n if (is.null(session_id)) {\n return(list())\n }\n}"}}
{"repo_name": "chatgpt", "file_name": "/chatgpt/R/generate_image.R", "inference_info": {"prefix_code": "#' Generate an Image With DALL-E 3\n#'\n#' @param prompt The prompt for image generation.\n#' @param out_file The path where to save the generated image.\n#' @param openai_api_key OpenAI's API key.\n#'\n#' @importFrom httr add_headers content content_type_json POST stop_for_status\n#' @importFrom jsonlite fromJSON toJSON\n#' @importFrom utils download.file\n#'\n#' @export\n#'\ngenerate_image <- ", "suffix_code": "\n", "middle_code": "function(prompt, out_file = tempfile(fileext = \".png\"),\n openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n post_res <- POST(\n paste0(api_url, \"/images/generations\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = toJSON(\n list(model = \"dall-e-3\", prompt = prompt, n = 1, size = \"1024x1024\"),\n auto_unbox = TRUE\n )\n )\n stop_for_status(post_res)\n download.file(fromJSON(content(post_res, as = \"text\", encoding = \"UTF-8\"))$data$url, out_file)\n return(out_file)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/chatgpt/R/list_models.R", "#' ChatGPT: List Models\n#'\n#' @param openai_api_key OpenAI's API key.\n#'\n#' @examples\n#' \\dontrun{\n#' list_models()\n#' }\n#'\n#' @importFrom httr add_headers content GET stop_for_status\n#' @importFrom jsonlite fromJSON\n#'\n#' @return A data.frame with the available models to be used by OpenAI's API.\n#'\n#' @export\n#'\nlist_models <- function(openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n get_res <- GET(\n paste0(api_url, \"/models\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key))\n )\n stop_for_status(get_res)\n fromJSON(content(get_res, as = \"text\", encoding = \"UTF-8\"))$data\n}\n"], ["/chatgpt/R/gpt_get_completions.R", "#' Get GPT Completions Endpoint\n#'\n#' @param prompt The prompt to generate completions for.\n#' @param openai_api_key OpenAI's API key.\n#' @param messages Available variable, to send the needed messages list to ChatGPT.\n#'\n#' @importFrom httr add_headers content content_type_json POST use_proxy\n#' @importFrom jsonlite toJSON\n#'\ngpt_get_completions <- function(prompt, openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"),\n messages = NULL) {\n if (nchar(openai_api_key) == 0) {\n stop(\"`OPENAI_API_KEY` not provided.\")\n }\n # See https://platform.openai.com/docs/api-reference/chat .\n params <- list(\n model = Sys.getenv(\"OPENAI_MODEL\", \"gpt-4o-mini\"),\n max_tokens = as.numeric(Sys.getenv(\"OPENAI_MAX_TOKENS\", 256)),\n temperature = as.numeric(Sys.getenv(\"OPENAI_TEMPERATURE\", 1)),\n top_p = as.numeric(Sys.getenv(\"OPENAI_TOP_P\", 1)),\n frequency_penalty = as.numeric(Sys.getenv(\"OPENAI_FREQUENCY_PENALTY\", 0)),\n presence_penalty = as.numeric(Sys.getenv(\"OPENAI_PRESENCE_PENALTY\", 0)),\n logprobs = as.logical(Sys.getenv(\"OPENAI_LOGPROBS\", FALSE))\n )\n if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT input:\\n\\n\", prompt, \"\\n\"))\n }\n return_language <- Sys.getenv(\"OPENAI_RETURN_LANGUAGE\")\n if (nchar(return_language) > 0) {\n return_language <- paste0(\"You return all your replies in \", return_language, \".\")\n }\n if (is.null(messages)) {\n messages <- list(\n list(\n role = \"system\",\n content = paste(\n \"You are a helpful assistant with extensive knowledge of R programming.\",\n return_language\n )\n ),\n list(role = \"user\", content = prompt)\n )\n } else {\n # If there are messages provided, then add the `return_language` if available.\n messages[[which(sapply(messages, function(message) message$role == \"system\"))]]$content <-\n paste(\n messages[[which(sapply(messages, function(message) message$role == \"system\"))]]$content,\n return_language\n )\n }\n # Get the proxy to use, if provided.\n proxy <- NULL\n if (nchar(Sys.getenv(\"OPENAI_PROXY\")) > 0) {\n proxy <- Sys.getenv(\"OPENAI_PROXY\")\n if (grepl(\"^(?:\\\\d{1,3}\\\\.){3}\\\\d{1,3}:\\\\d{2,5}$\", proxy)) {\n proxy <- use_proxy(gsub(\":.*\", \"\", proxy), as.numeric(gsub(\".*:\", \"\", proxy)))\n } else {\n stop(\"Invalid proxy provided in `OPENAI_PROXY`: \", proxy)\n }\n }\n # Run the API query.\n final_res <- list()\n keep_querying <- TRUE\n while (keep_querying) {\n post_res <- POST(\n paste0(api_url, \"/chat/completions\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = toJSON(c(params, list(messages = messages)), auto_unbox = TRUE),\n proxy\n )\n if (!post_res$status_code %in% 200:299) {\n stop(content(post_res))\n }\n if (get_verbosity() > 1) {\n # If verbose is over 1, show the ongoing GPT response.\n message(content(post_res, as = \"text\", encoding = \"UTF-8\"))\n }\n post_res <- content(post_res)\n final_res <- append(final_res, list(post_res))\n # In the case the finish_reason is the length of the message, then we need to keep querying.\n keep_querying <- all(sapply(post_res$choices, function(x) x$finish_reason == \"length\"))\n # And update the messages sent to ChatGPT, in order to continue the current session.\n messages <- append(\n append(\n messages,\n list(list(role = \"assistant\", content = parse_response(list(post_res), verbosity = 0)))\n ),\n list(list(role = \"user\", content = \"continue\"))\n )\n }\n final_res\n}\n"], ["/chatgpt/R/ask_chatgpt.R", "#' Ask ChatGPT\n#'\n#' Note: See also `reset_chat_session`.\n#'\n#' @param question The question to ask ChatGPT.\n#' @param session_id The ID of the session to be used. We can have different conversations by using\n#' different session IDs.\n#' @param openai_api_key OpenAI's API key.\n#' @param images A list of images to attach to the question. It could be a list of URLs or paths.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(ask_chatgpt(\"What do you think about R language?\"))\n#' }\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nask_chatgpt <- function(question, session_id = \"1\", openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"),\n images = NULL) {\n # Get the existing chat session messages, and add the new message.\n chat_session_messages <- append(get_chat_session(session_id), list(\n list(role = \"user\", content = build_prompt_content(question, images))\n ))\n # Send the query to ChatGPT.\n chat_gpt_reply <- parse_response(\n gpt_get_completions(question, openai_api_key, chat_session_messages)\n )\n chat_session_messages <- append(chat_session_messages, list(\n list(role = \"assistant\", content = chat_gpt_reply)\n ))\n # Update the chat session messages with the new question and the reply.\n reset_chat_session(chat_session_messages, session_id)\n chat_gpt_reply\n}\n"], ["/chatgpt/R/addins.R", "#' Run a ChatGPT RStudio Addin\n#'\n#' @param addin_name The name of the adding to execute.\n#'\n#' @importFrom rstudioapi as.document_range getActiveDocumentContext modifyRange\n#'\nrun_addin <- function(addin_name) {\n # Select which addin has to be used.\n addin_function <- switch(addin_name,\n \"comment_code\" = comment_code,\n \"complete_code\" = complete_code,\n \"create_unit_tests\" = create_unit_tests,\n \"create_variable_name\" = create_variable_name,\n \"document_code\" = document_code,\n \"explain_code\" = explain_code,\n \"find_issues_in_code\" = find_issues_in_code,\n \"optimize_code\" = optimize_code,\n \"refactor_code\" = refactor_code,\n stop(\"`addin_name` not found.\")\n )\n # Get the selected code.\n doc_context <- getActiveDocumentContext()\n selected_code <- doc_context$selection[[1]]$text\n is_full_file <- all(nchar(selected_code) == 0)\n # If no code is selected, use the whole file.\n if (is_full_file) {\n selected_code <- doc_context$contents\n }\n selected_code <- paste0(selected_code, collapse = \"\\n\")\n # Apply the addin function.\n out <- addin_function(selected_code)\n if (as.logical(Sys.getenv(\"OPENAI_ADDIN_REPLACE\", FALSE))) {\n doc_range <- doc_context$selection[[1]]$range\n if (is_full_file) {\n doc_range <- as.document_range(c(c(0, 0), c(Inf, Inf)))\n }\n modifyRange(doc_range, out, doc_context$id)\n } else if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT output:\\n\\n\", out, \"\\n\"))\n } else {\n warning(\"Please set one of `OPENAI_ADDIN_REPLACE=TRUE` or `OPENAI_VERBOSE=TRUE`\")\n }\n invisible(NULL)\n}\n\nrun_addin_comment_code <- function() run_addin(\"comment_code\")\nrun_addin_complete_code <- function() run_addin(\"complete_code\")\nrun_addin_create_unit_tests <- function() run_addin(\"create_unit_tests\")\nrun_addin_create_variable_name <- function() run_addin(\"create_variable_name\")\nrun_addin_document_code <- function() run_addin(\"document_code\")\nrun_addin_explain_code <- function() run_addin(\"explain_code\")\nrun_addin_find_issues_in_code <- function() run_addin(\"find_issues_in_code\")\nrun_addin_optimize_code <- function() run_addin(\"optimize_code\")\nrun_addin_refactor_code <- function() run_addin(\"refactor_code\")\n\n#' Ask ChatGPT\n#'\n#' Opens an interactive chat session with ChatGPT\n#'\n#' @importFrom miniUI gadgetTitleBar miniPage\n#' @importFrom shiny actionButton br icon observeEvent onStop runGadget stopApp textAreaInput\n#' @importFrom shiny updateTextAreaInput wellPanel\n#' @importFrom utils getFromNamespace\n#'\nrun_addin_ask_chatgpt <- function() {\n reset_chat_session()\n ui <- miniPage(wellPanel(\n gadgetTitleBar(\"Ask ChatGPT\", NULL),\n textAreaInput(\"question\", \"Question:\", width = \"100%\", height = \"150px\"),\n actionButton(\"ask_button\", \"Ask\", icon(\"paper-plane\")),\n br(), br(),\n textAreaInput(\"answer\", \"Answer:\", width = \"100%\", height = \"150px\")\n ))\n server <- function(input, output, session) {\n observeEvent(input$ask_button, {\n chatgpt_reply <- ask_chatgpt(input$question)\n if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT output:\\n\\n\", chatgpt_reply, \"\\n\"))\n }\n updateTextAreaInput(session, \"answer\", value = chatgpt_reply)\n })\n observeEvent(input$done, {\n reset_chat_session()\n stopApp()\n })\n onStop(reset_chat_session)\n }\n runGadget(ui, server)\n}\n"], ["/chatgpt/R/build_prompt_content.R", "#' Build Prompt Content\n#'\n#' @param question The question to ask ChatGPT.\n#' @param images A list of images to attach to the question. It could be a list of URLs or paths.\n#'\n#' @importFrom xfun base64_encode\n#'\nbuild_prompt_content <- function(question, images) {\n if (length(images) == 0) {\n return(question)\n }\n prompt_content <- list(list(type = \"text\", text = question))\n append(prompt_content, lapply(images, function(image) {\n # If it's a local file, then transform it to base 64 encoding. If not, return the \"URL\".\n image_url <- image\n if (file.exists(image)) {\n image_url <- paste0(\"data:image/jpeg;base64,\", base64_encode(image))\n }\n list(type = \"image_url\", image_url = list(url = image_url))\n }))\n}\n"], ["/chatgpt/R/parse_response.R", "#' Parse OpenAI API Response\n#'\n#' Takes the raw response from the OpenAI API and extracts the text content from it.\n#'\n#' @param raw_responses The raw response object returned by the OpenAI API.\n#' @param verbosity The verbosity level for this function.\n#'\n#' @return Returns a character vector containing the text content of the response.\n#'\nparse_response <- function(raw_responses, verbosity = get_verbosity()) {\n # Parse the message content of the list of raw_responses. Trim those messages, and paste them.\n parsed_response <- paste(trimws(sapply(raw_responses, function(response) {\n sapply(response$choices, function(x) x$message$content)\n })), collapse = \"\")\n if (verbosity > 2) {\n # If we are in 3-verbose mode, add the raw_responses as an attribute to the return object.\n attr(parsed_response, \"raw_responses\") <- raw_responses\n }\n parsed_response\n}\n"], ["/chatgpt/R/create_unit_tests.R", "#' ChatGPT: Create Unit Tests\n#'\n#' Create `{testthat}` test cases for the code.\n#'\n#' @param code The code for which to create unit tests by ChatGPT. If not provided, it will use\n#' what's copied on the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(create_unit_tests(\"squared_numbers <- function(numbers) {\\n numbers ^ 2\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncreate_unit_tests <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0(\n \"Using testthat 3e, version over 3.0.0, create a full testthat file, with test cases for the \",\n 'following R code: \"', code, '\"'\n )\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/chatgpt-package.R", "#' 'OpenAI's 'ChatGPT' <https://chat.openai.com/> coding assistant for 'RStudio'. A set\n#' of functions and 'RStudio' addins that aim to help the R developer in tedious coding tasks.\n#'\n\"_PACKAGE\"\n\n.state <- new.env(parent = emptyenv())\n\n# Empty chat session messages at startup.\nassign(\"chat_session_messages\", list(), envir = .state)\n\napi_url <- Sys.getenv(\"OPENAI_API_URL\", \"https://api.openai.com/v1\")\n"], ["/chatgpt/R/reset_chat_session.R", "#' Reset Chat Session\n#'\n#' This function is intended to be used with `ask_chatgpt`. If we are using `ask_chatgpt` to chat with ChatGPT, and\n#' we want to start a new conversation, we must call `reset_chat_session`.\n#'\n#' @param system_role ChatGPT's role as an AI assistant.\n#' @param session_id The ID of the session to be used. If `NULL`, this function will have no effect.\n#'\n#' @export\n#'\nreset_chat_session <- function(system_role = \"You are a helpful assistant.\", session_id = \"1\") {\n if (is.null(session_id)) {\n return()\n }\n if (is.list(system_role)) {\n # If `system_role` is a list, then it is a ChatGPT session object.\n session <- system_role\n } else {\n # Otherwise, it's a string specifying ChatGPT's role.\n session <- list(list(role = \"system\", content = system_role))\n }\n all_sessions <- get(\"chat_session_messages\", envir = .state)\n all_sessions[[as.character(session_id)]] <- session\n assign(\"chat_session_messages\", all_sessions, envir = .state)\n}\n"], ["/chatgpt/R/get_chat_session.R", "#' Get Chat Session\n#'\n#' @param session_id The ID of the session to be used. If `NULL`, it will return an empty session.\n#'\nget_chat_session <- function(session_id = \"1\") {\n default_session <- list(list(role = \"system\", content = \"You are a helpful assistant.\"))\n if (is.null(session_id)) {\n return(default_session)\n }\n session <- get(\"chat_session_messages\", envir = .state)[[as.character(session_id)]]\n # If the session was not found, then it's a new (default) session.\n if (is.null(session)) {\n session <- default_session\n }\n session\n}\n"], ["/chatgpt/R/get_verbosity.R", "#' Get Verbosity Level\n#'\nget_verbosity <- function() {\n # `OPENAI_VERBOSE` should be one of `numeric` or `FALSE`/`TRUE`. But we'll return it as numeric.\n suppressWarnings(max(\n as.logical(Sys.getenv(\"OPENAI_VERBOSE\", TRUE)),\n as.numeric(Sys.getenv(\"OPENAI_VERBOSE\", TRUE)),\n na.rm = TRUE\n ))\n}\n"], ["/chatgpt/R/create_variable_name.R", "#' ChatGPT: Create Variable Name\n#'\n#' @param code The code for which to give a variable name to its result. If not provided, it will\n#' use what's copied on the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(create_variable_name(\"sapply(1:10, function(i) i ** 2)\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncreate_variable_name <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Give a good variable name to the result of the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/document_code.R", "#' ChatGPT: Document Code (in roxygen2 format)\n#'\n#' @param code The code to be documented by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(document_code(\"square_numbers <- function(numbers) numbers ** 2\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ndocument_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Document, in roxygen2 format, this R function: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/explain_code.R", "#' ChatGPT: Explain Code\n#'\n#' @param code The code to be explained by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(explain_code(\"for (i in 1:10) {\\n print(i ** 2)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nexplain_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Explain the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/comment_code.R", "#' ChatGPT: Comment Code\n#'\n#' @param code The code to be commented by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(comment_code(\"for (i in 1:10) {\\n print(i ** 2)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncomment_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Add inline comments to the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/optimize_code.R", "#' ChatGPT: Optimize Code\n#'\n#' @param code The code to be optimized by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(optimize_code(\"i <- 10\\nwhile (i > 0) {\\n i <- i - 1\\n print(i)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\noptimize_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Optimize the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/refactor_code.R", "#' ChatGPT: Refactor Code\n#'\n#' @param code The code to be refactored by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(refactor_code(\"i <- 10\\nwhile (i > 0) {\\n i <- i - 1\\n print(i)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nrefactor_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Refactor the following R code, returning valid R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/find_issues_in_code.R", "#' ChatGPT: Find Issues in Code\n#'\n#' @param code The code to be analyzed by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(find_issues_in_code(\"i <- 0\\nwhile (i < 0) {\\n i <- i - 1\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nfind_issues_in_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Find issues or bugs in the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/complete_code.R", "#' ChatGPT: Complete Code\n#'\n#' @param code The code to be completed by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(complete_code(\"# A function to square each element of a vector\\nsquare_each <- function(\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncomplete_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Complete the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:11:04", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(prompt, out_file = tempfile(fileext = \".png\"),\n openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {}", "code_description": "This code segment functions to: Submit a request to an external AI service for visual content creation based on textual input, process the API response to retrieve the generated resource, and download the resulting media asset to local storage while handling authorization and error checking."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(prompt, out_file = tempfile(fileext = \".png\"),\n openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n if (missing(prompt) || nchar(prompt) == 0) {\n stop(\"A text prompt must be specified\")\n }\n \n if (nchar(openai_api_key) == 0) {\n stop(\"API key required in openai_api_key parameter or OPENAI_API_KEY environment variable\")\n }\n \n response <- httr::POST(\n url = \"https://api.openai.com/v1/images/generations\",\n httr::add_headers(\n \"Authorization\" = paste(\"Bearer\", openai_api_key),\n \"Content-Type\" = \"application/json\"\n ),\n body = jsonlite::toJSON(list(\n model = \"dall-e-3\",\n prompt = prompt,\n n = 1,\n size = \"1024x1024\"\n ), auto_unbox = TRUE)\n )\n \n httr::stop_for_status(response)\n parsed <- jsonlite::fromJSON(httr::content(response, \"text\", encoding = \"UTF-8\"))\n image_url <- parsed$data$url\n \n utils::download.file(image_url, out_file, mode = \"wb\")\n invisible(out_file)\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-11-30"}, "editdistance_info": {"edit_distance": 37.1747, "calculate_time": "2025-08-21 01:11:30", "true_code_clean": "function(prompt, out_file = tempfile(fileext = \".png\"),\n openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n post_res <- POST(\n paste0(api_url, \"/images/generations\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = toJSON(\n list(model = \"dall-e-3\", prompt = prompt, n = 1, size = \"1024x1024\"),\n auto_unbox = TRUE\n )\n )\n stop_for_status(post_res)\n download.file(fromJSON(content(post_res, as = \"text\", encoding = \"UTF-8\"))$data$url, out_file)\n return(out_file)\n}", "predict_code_clean": "function(prompt, out_file = tempfile(fileext = \".png\"),\n openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n if (missing(prompt) || nchar(prompt) == 0) {\n stop(\"A text prompt must be specified\")\n }\n if (nchar(openai_api_key) == 0) {\n stop(\"API key required in openai_api_key parameter or OPENAI_API_KEY environment variable\")\n }\n response <- httr::POST(\n url = \"https://api.openai.com/v1/images/generations\",\n httr::add_headers(\n \"Authorization\" = paste(\"Bearer\", openai_api_key),\n \"Content-Type\" = \"application/json\"\n ),\n body = jsonlite::toJSON(list(\n model = \"dall-e-3\",\n prompt = prompt,\n n = 1,\n size = \"1024x1024\"\n ), auto_unbox = TRUE)\n )\n httr::stop_for_status(response)\n parsed <- jsonlite::fromJSON(httr::content(response, \"text\", encoding = \"UTF-8\"))\n image_url <- parsed$data$url\n utils::download.file(image_url, out_file, mode = \"wb\")\n invisible(out_file)\n}"}}
{"repo_name": "chatgpt", "file_name": "/chatgpt/R/gpt_get_completions.R", "inference_info": {"prefix_code": "#' Get GPT Completions Endpoint\n#'\n#' @param prompt The prompt to generate completions for.\n#' @param openai_api_key OpenAI's API key.\n#' @param messages Available variable, to send the needed messages list to ChatGPT.\n#'\n#' @importFrom httr add_headers content content_type_json POST use_proxy\n#' @importFrom jsonlite toJSON\n#'\ngpt_get_completions <- ", "suffix_code": "\n", "middle_code": "function(prompt, openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"),\n messages = NULL) {\n if (nchar(openai_api_key) == 0) {\n stop(\"`OPENAI_API_KEY` not provided.\")\n }\n params <- list(\n model = Sys.getenv(\"OPENAI_MODEL\", \"gpt-4o-mini\"),\n max_tokens = as.numeric(Sys.getenv(\"OPENAI_MAX_TOKENS\", 256)),\n temperature = as.numeric(Sys.getenv(\"OPENAI_TEMPERATURE\", 1)),\n top_p = as.numeric(Sys.getenv(\"OPENAI_TOP_P\", 1)),\n frequency_penalty = as.numeric(Sys.getenv(\"OPENAI_FREQUENCY_PENALTY\", 0)),\n presence_penalty = as.numeric(Sys.getenv(\"OPENAI_PRESENCE_PENALTY\", 0)),\n logprobs = as.logical(Sys.getenv(\"OPENAI_LOGPROBS\", FALSE))\n )\n if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT input:\\n\\n\", prompt, \"\\n\"))\n }\n return_language <- Sys.getenv(\"OPENAI_RETURN_LANGUAGE\")\n if (nchar(return_language) > 0) {\n return_language <- paste0(\"You return all your replies in \", return_language, \".\")\n }\n if (is.null(messages)) {\n messages <- list(\n list(\n role = \"system\",\n content = paste(\n \"You are a helpful assistant with extensive knowledge of R programming.\",\n return_language\n )\n ),\n list(role = \"user\", content = prompt)\n )\n } else {\n messages[[which(sapply(messages, function(message) message$role == \"system\"))]]$content <-\n paste(\n messages[[which(sapply(messages, function(message) message$role == \"system\"))]]$content,\n return_language\n )\n }\n proxy <- NULL\n if (nchar(Sys.getenv(\"OPENAI_PROXY\")) > 0) {\n proxy <- Sys.getenv(\"OPENAI_PROXY\")\n if (grepl(\"^(?:\\\\d{1,3}\\\\.){3}\\\\d{1,3}:\\\\d{2,5}$\", proxy)) {\n proxy <- use_proxy(gsub(\":.*\", \"\", proxy), as.numeric(gsub(\".*:\", \"\", proxy)))\n } else {\n stop(\"Invalid proxy provided in `OPENAI_PROXY`: \", proxy)\n }\n }\n final_res <- list()\n keep_querying <- TRUE\n while (keep_querying) {\n post_res <- POST(\n paste0(api_url, \"/chat/completions\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = toJSON(c(params, list(messages = messages)), auto_unbox = TRUE),\n proxy\n )\n if (!post_res$status_code %in% 200:299) {\n stop(content(post_res))\n }\n if (get_verbosity() > 1) {\n message(content(post_res, as = \"text\", encoding = \"UTF-8\"))\n }\n post_res <- content(post_res)\n final_res <- append(final_res, list(post_res))\n keep_querying <- all(sapply(post_res$choices, function(x) x$finish_reason == \"length\"))\n messages <- append(\n append(\n messages,\n list(list(role = \"assistant\", content = parse_response(list(post_res), verbosity = 0)))\n ),\n list(list(role = \"user\", content = \"continue\"))\n )\n }\n final_res\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/chatgpt/R/generate_image.R", "#' Generate an Image With DALL-E 3\n#'\n#' @param prompt The prompt for image generation.\n#' @param out_file The path where to save the generated image.\n#' @param openai_api_key OpenAI's API key.\n#'\n#' @importFrom httr add_headers content content_type_json POST stop_for_status\n#' @importFrom jsonlite fromJSON toJSON\n#' @importFrom utils download.file\n#'\n#' @export\n#'\ngenerate_image <- function(prompt, out_file = tempfile(fileext = \".png\"),\n openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n post_res <- POST(\n paste0(api_url, \"/images/generations\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = toJSON(\n list(model = \"dall-e-3\", prompt = prompt, n = 1, size = \"1024x1024\"),\n auto_unbox = TRUE\n )\n )\n stop_for_status(post_res)\n download.file(fromJSON(content(post_res, as = \"text\", encoding = \"UTF-8\"))$data$url, out_file)\n return(out_file)\n}\n"], ["/chatgpt/R/list_models.R", "#' ChatGPT: List Models\n#'\n#' @param openai_api_key OpenAI's API key.\n#'\n#' @examples\n#' \\dontrun{\n#' list_models()\n#' }\n#'\n#' @importFrom httr add_headers content GET stop_for_status\n#' @importFrom jsonlite fromJSON\n#'\n#' @return A data.frame with the available models to be used by OpenAI's API.\n#'\n#' @export\n#'\nlist_models <- function(openai_api_key = Sys.getenv(\"OPENAI_API_KEY\")) {\n get_res <- GET(\n paste0(api_url, \"/models\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key))\n )\n stop_for_status(get_res)\n fromJSON(content(get_res, as = \"text\", encoding = \"UTF-8\"))$data\n}\n"], ["/chatgpt/R/addins.R", "#' Run a ChatGPT RStudio Addin\n#'\n#' @param addin_name The name of the adding to execute.\n#'\n#' @importFrom rstudioapi as.document_range getActiveDocumentContext modifyRange\n#'\nrun_addin <- function(addin_name) {\n # Select which addin has to be used.\n addin_function <- switch(addin_name,\n \"comment_code\" = comment_code,\n \"complete_code\" = complete_code,\n \"create_unit_tests\" = create_unit_tests,\n \"create_variable_name\" = create_variable_name,\n \"document_code\" = document_code,\n \"explain_code\" = explain_code,\n \"find_issues_in_code\" = find_issues_in_code,\n \"optimize_code\" = optimize_code,\n \"refactor_code\" = refactor_code,\n stop(\"`addin_name` not found.\")\n )\n # Get the selected code.\n doc_context <- getActiveDocumentContext()\n selected_code <- doc_context$selection[[1]]$text\n is_full_file <- all(nchar(selected_code) == 0)\n # If no code is selected, use the whole file.\n if (is_full_file) {\n selected_code <- doc_context$contents\n }\n selected_code <- paste0(selected_code, collapse = \"\\n\")\n # Apply the addin function.\n out <- addin_function(selected_code)\n if (as.logical(Sys.getenv(\"OPENAI_ADDIN_REPLACE\", FALSE))) {\n doc_range <- doc_context$selection[[1]]$range\n if (is_full_file) {\n doc_range <- as.document_range(c(c(0, 0), c(Inf, Inf)))\n }\n modifyRange(doc_range, out, doc_context$id)\n } else if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT output:\\n\\n\", out, \"\\n\"))\n } else {\n warning(\"Please set one of `OPENAI_ADDIN_REPLACE=TRUE` or `OPENAI_VERBOSE=TRUE`\")\n }\n invisible(NULL)\n}\n\nrun_addin_comment_code <- function() run_addin(\"comment_code\")\nrun_addin_complete_code <- function() run_addin(\"complete_code\")\nrun_addin_create_unit_tests <- function() run_addin(\"create_unit_tests\")\nrun_addin_create_variable_name <- function() run_addin(\"create_variable_name\")\nrun_addin_document_code <- function() run_addin(\"document_code\")\nrun_addin_explain_code <- function() run_addin(\"explain_code\")\nrun_addin_find_issues_in_code <- function() run_addin(\"find_issues_in_code\")\nrun_addin_optimize_code <- function() run_addin(\"optimize_code\")\nrun_addin_refactor_code <- function() run_addin(\"refactor_code\")\n\n#' Ask ChatGPT\n#'\n#' Opens an interactive chat session with ChatGPT\n#'\n#' @importFrom miniUI gadgetTitleBar miniPage\n#' @importFrom shiny actionButton br icon observeEvent onStop runGadget stopApp textAreaInput\n#' @importFrom shiny updateTextAreaInput wellPanel\n#' @importFrom utils getFromNamespace\n#'\nrun_addin_ask_chatgpt <- function() {\n reset_chat_session()\n ui <- miniPage(wellPanel(\n gadgetTitleBar(\"Ask ChatGPT\", NULL),\n textAreaInput(\"question\", \"Question:\", width = \"100%\", height = \"150px\"),\n actionButton(\"ask_button\", \"Ask\", icon(\"paper-plane\")),\n br(), br(),\n textAreaInput(\"answer\", \"Answer:\", width = \"100%\", height = \"150px\")\n ))\n server <- function(input, output, session) {\n observeEvent(input$ask_button, {\n chatgpt_reply <- ask_chatgpt(input$question)\n if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT output:\\n\\n\", chatgpt_reply, \"\\n\"))\n }\n updateTextAreaInput(session, \"answer\", value = chatgpt_reply)\n })\n observeEvent(input$done, {\n reset_chat_session()\n stopApp()\n })\n onStop(reset_chat_session)\n }\n runGadget(ui, server)\n}\n"], ["/chatgpt/R/get_verbosity.R", "#' Get Verbosity Level\n#'\nget_verbosity <- function() {\n # `OPENAI_VERBOSE` should be one of `numeric` or `FALSE`/`TRUE`. But we'll return it as numeric.\n suppressWarnings(max(\n as.logical(Sys.getenv(\"OPENAI_VERBOSE\", TRUE)),\n as.numeric(Sys.getenv(\"OPENAI_VERBOSE\", TRUE)),\n na.rm = TRUE\n ))\n}\n"], ["/chatgpt/R/ask_chatgpt.R", "#' Ask ChatGPT\n#'\n#' Note: See also `reset_chat_session`.\n#'\n#' @param question The question to ask ChatGPT.\n#' @param session_id The ID of the session to be used. We can have different conversations by using\n#' different session IDs.\n#' @param openai_api_key OpenAI's API key.\n#' @param images A list of images to attach to the question. It could be a list of URLs or paths.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(ask_chatgpt(\"What do you think about R language?\"))\n#' }\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nask_chatgpt <- function(question, session_id = \"1\", openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"),\n images = NULL) {\n # Get the existing chat session messages, and add the new message.\n chat_session_messages <- append(get_chat_session(session_id), list(\n list(role = \"user\", content = build_prompt_content(question, images))\n ))\n # Send the query to ChatGPT.\n chat_gpt_reply <- parse_response(\n gpt_get_completions(question, openai_api_key, chat_session_messages)\n )\n chat_session_messages <- append(chat_session_messages, list(\n list(role = \"assistant\", content = chat_gpt_reply)\n ))\n # Update the chat session messages with the new question and the reply.\n reset_chat_session(chat_session_messages, session_id)\n chat_gpt_reply\n}\n"], ["/chatgpt/R/parse_response.R", "#' Parse OpenAI API Response\n#'\n#' Takes the raw response from the OpenAI API and extracts the text content from it.\n#'\n#' @param raw_responses The raw response object returned by the OpenAI API.\n#' @param verbosity The verbosity level for this function.\n#'\n#' @return Returns a character vector containing the text content of the response.\n#'\nparse_response <- function(raw_responses, verbosity = get_verbosity()) {\n # Parse the message content of the list of raw_responses. Trim those messages, and paste them.\n parsed_response <- paste(trimws(sapply(raw_responses, function(response) {\n sapply(response$choices, function(x) x$message$content)\n })), collapse = \"\")\n if (verbosity > 2) {\n # If we are in 3-verbose mode, add the raw_responses as an attribute to the return object.\n attr(parsed_response, \"raw_responses\") <- raw_responses\n }\n parsed_response\n}\n"], ["/chatgpt/R/build_prompt_content.R", "#' Build Prompt Content\n#'\n#' @param question The question to ask ChatGPT.\n#' @param images A list of images to attach to the question. It could be a list of URLs or paths.\n#'\n#' @importFrom xfun base64_encode\n#'\nbuild_prompt_content <- function(question, images) {\n if (length(images) == 0) {\n return(question)\n }\n prompt_content <- list(list(type = \"text\", text = question))\n append(prompt_content, lapply(images, function(image) {\n # If it's a local file, then transform it to base 64 encoding. If not, return the \"URL\".\n image_url <- image\n if (file.exists(image)) {\n image_url <- paste0(\"data:image/jpeg;base64,\", base64_encode(image))\n }\n list(type = \"image_url\", image_url = list(url = image_url))\n }))\n}\n"], ["/chatgpt/R/reset_chat_session.R", "#' Reset Chat Session\n#'\n#' This function is intended to be used with `ask_chatgpt`. If we are using `ask_chatgpt` to chat with ChatGPT, and\n#' we want to start a new conversation, we must call `reset_chat_session`.\n#'\n#' @param system_role ChatGPT's role as an AI assistant.\n#' @param session_id The ID of the session to be used. If `NULL`, this function will have no effect.\n#'\n#' @export\n#'\nreset_chat_session <- function(system_role = \"You are a helpful assistant.\", session_id = \"1\") {\n if (is.null(session_id)) {\n return()\n }\n if (is.list(system_role)) {\n # If `system_role` is a list, then it is a ChatGPT session object.\n session <- system_role\n } else {\n # Otherwise, it's a string specifying ChatGPT's role.\n session <- list(list(role = \"system\", content = system_role))\n }\n all_sessions <- get(\"chat_session_messages\", envir = .state)\n all_sessions[[as.character(session_id)]] <- session\n assign(\"chat_session_messages\", all_sessions, envir = .state)\n}\n"], ["/chatgpt/R/get_chat_session.R", "#' Get Chat Session\n#'\n#' @param session_id The ID of the session to be used. If `NULL`, it will return an empty session.\n#'\nget_chat_session <- function(session_id = \"1\") {\n default_session <- list(list(role = \"system\", content = \"You are a helpful assistant.\"))\n if (is.null(session_id)) {\n return(default_session)\n }\n session <- get(\"chat_session_messages\", envir = .state)[[as.character(session_id)]]\n # If the session was not found, then it's a new (default) session.\n if (is.null(session)) {\n session <- default_session\n }\n session\n}\n"], ["/chatgpt/R/chatgpt-package.R", "#' 'OpenAI's 'ChatGPT' <https://chat.openai.com/> coding assistant for 'RStudio'. A set\n#' of functions and 'RStudio' addins that aim to help the R developer in tedious coding tasks.\n#'\n\"_PACKAGE\"\n\n.state <- new.env(parent = emptyenv())\n\n# Empty chat session messages at startup.\nassign(\"chat_session_messages\", list(), envir = .state)\n\napi_url <- Sys.getenv(\"OPENAI_API_URL\", \"https://api.openai.com/v1\")\n"], ["/chatgpt/R/create_unit_tests.R", "#' ChatGPT: Create Unit Tests\n#'\n#' Create `{testthat}` test cases for the code.\n#'\n#' @param code The code for which to create unit tests by ChatGPT. If not provided, it will use\n#' what's copied on the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(create_unit_tests(\"squared_numbers <- function(numbers) {\\n numbers ^ 2\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncreate_unit_tests <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0(\n \"Using testthat 3e, version over 3.0.0, create a full testthat file, with test cases for the \",\n 'following R code: \"', code, '\"'\n )\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/create_variable_name.R", "#' ChatGPT: Create Variable Name\n#'\n#' @param code The code for which to give a variable name to its result. If not provided, it will\n#' use what's copied on the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(create_variable_name(\"sapply(1:10, function(i) i ** 2)\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncreate_variable_name <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Give a good variable name to the result of the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/optimize_code.R", "#' ChatGPT: Optimize Code\n#'\n#' @param code The code to be optimized by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(optimize_code(\"i <- 10\\nwhile (i > 0) {\\n i <- i - 1\\n print(i)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\noptimize_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Optimize the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/explain_code.R", "#' ChatGPT: Explain Code\n#'\n#' @param code The code to be explained by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(explain_code(\"for (i in 1:10) {\\n print(i ** 2)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nexplain_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Explain the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/comment_code.R", "#' ChatGPT: Comment Code\n#'\n#' @param code The code to be commented by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(comment_code(\"for (i in 1:10) {\\n print(i ** 2)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncomment_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Add inline comments to the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/refactor_code.R", "#' ChatGPT: Refactor Code\n#'\n#' @param code The code to be refactored by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(refactor_code(\"i <- 10\\nwhile (i > 0) {\\n i <- i - 1\\n print(i)\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nrefactor_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Refactor the following R code, returning valid R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/document_code.R", "#' ChatGPT: Document Code (in roxygen2 format)\n#'\n#' @param code The code to be documented by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(document_code(\"square_numbers <- function(numbers) numbers ** 2\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ndocument_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Document, in roxygen2 format, this R function: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/find_issues_in_code.R", "#' ChatGPT: Find Issues in Code\n#'\n#' @param code The code to be analyzed by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(find_issues_in_code(\"i <- 0\\nwhile (i < 0) {\\n i <- i - 1\\n}\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\nfind_issues_in_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Find issues or bugs in the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"], ["/chatgpt/R/complete_code.R", "#' ChatGPT: Complete Code\n#'\n#' @param code The code to be completed by ChatGPT. If not provided, it will use what's copied on\n#' the clipboard.\n#'\n#' @examples\n#' \\dontrun{\n#' cat(complete_code(\"# A function to square each element of a vector\\nsquare_each <- function(\"))\n#' }\n#'\n#' @importFrom clipr read_clip\n#'\n#' @return A character value with the response generated by ChatGPT.\n#'\n#' @export\n#'\ncomplete_code <- function(code = clipr::read_clip(allow_non_interactive = TRUE)) {\n code <- paste(gsub('\"', \"'\", code), collapse = \"\\n\")\n prompt <- paste0('Complete the following R code: \"', code, '\"')\n parse_response(gpt_get_completions(prompt))\n}\n"]], "task_instance_info": {"created_time": "2025-08-21 01:11:04", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(prompt, openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"),\n messages = NULL) {}", "code_description": "This code segment functions to: Configure and execute iterative API requests to a language model service using specified parameters, handle response validation and continuation tokens, and manage system-level configurations including proxy settings and localization preferences."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(prompt, openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"), messages = NULL) {\n if (is.null(messages)) {\n messages <- list(list(role = \"user\", content = prompt))\n }\n \n body <- list(\n model = \"gpt-3.5-turbo\",\n messages = messages\n )\n \n response <- POST(\n url = \"https://api.openai.com/v1/chat/completions\",\n add_headers(Authorization = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = jsonlite::toJSON(body, auto_unbox = TRUE)\n )\n \n if (response$status_code != 200) {\n stop(content(response, \"text\", encoding = \"UTF-8\"))\n }\n \n content <- jsonlite::fromJSON(content(response, \"text\", encoding = \"UTF-8\"))\n return(content$choices[[1]]$message$content)\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 01-11-35"}, "editdistance_info": {"edit_distance": 14.531, "calculate_time": "2025-08-21 01:11:35", "true_code_clean": "function(prompt, openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"),\n messages = NULL) {\n if (nchar(openai_api_key) == 0) {\n stop(\"`OPENAI_API_KEY` not provided.\")\n }\n params <- list(\n model = Sys.getenv(\"OPENAI_MODEL\", \"gpt-4o-mini\"),\n max_tokens = as.numeric(Sys.getenv(\"OPENAI_MAX_TOKENS\", 256)),\n temperature = as.numeric(Sys.getenv(\"OPENAI_TEMPERATURE\", 1)),\n top_p = as.numeric(Sys.getenv(\"OPENAI_TOP_P\", 1)),\n frequency_penalty = as.numeric(Sys.getenv(\"OPENAI_FREQUENCY_PENALTY\", 0)),\n presence_penalty = as.numeric(Sys.getenv(\"OPENAI_PRESENCE_PENALTY\", 0)),\n logprobs = as.logical(Sys.getenv(\"OPENAI_LOGPROBS\", FALSE))\n )\n if (get_verbosity()) {\n message(paste0(\"\\n*** ChatGPT input:\\n\\n\", prompt, \"\\n\"))\n }\n return_language <- Sys.getenv(\"OPENAI_RETURN_LANGUAGE\")\n if (nchar(return_language) > 0) {\n return_language <- paste0(\"You return all your replies in \", return_language, \".\")\n }\n if (is.null(messages)) {\n messages <- list(\n list(\n role = \"system\",\n content = paste(\n \"You are a helpful assistant with extensive knowledge of R programming.\",\n return_language\n )\n ),\n list(role = \"user\", content = prompt)\n )\n } else {\n messages[[which(sapply(messages, function(message) message$role == \"system\"))]]$content <-\n paste(\n messages[[which(sapply(messages, function(message) message$role == \"system\"))]]$content,\n return_language\n )\n }\n proxy <- NULL\n if (nchar(Sys.getenv(\"OPENAI_PROXY\")) > 0) {\n proxy <- Sys.getenv(\"OPENAI_PROXY\")\n if (grepl(\"^(?:\\\\d{1,3}\\\\.){3}\\\\d{1,3}:\\\\d{2,5}$\", proxy)) {\n proxy <- use_proxy(gsub(\":.*\", \"\", proxy), as.numeric(gsub(\".*:\", \"\", proxy)))\n } else {\n stop(\"Invalid proxy provided in `OPENAI_PROXY`: \", proxy)\n }\n }\n final_res <- list()\n keep_querying <- TRUE\n while (keep_querying) {\n post_res <- POST(\n paste0(api_url, \"/chat/completions\"),\n add_headers(\"Authorization\" = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = toJSON(c(params, list(messages = messages)), auto_unbox = TRUE),\n proxy\n )\n if (!post_res$status_code %in% 200:299) {\n stop(content(post_res))\n }\n if (get_verbosity() > 1) {\n message(content(post_res, as = \"text\", encoding = \"UTF-8\"))\n }\n post_res <- content(post_res)\n final_res <- append(final_res, list(post_res))\n keep_querying <- all(sapply(post_res$choices, function(x) x$finish_reason == \"length\"))\n messages <- append(\n append(\n messages,\n list(list(role = \"assistant\", content = parse_response(list(post_res), verbosity = 0)))\n ),\n list(list(role = \"user\", content = \"continue\"))\n )\n }\n final_res\n}", "predict_code_clean": "function(prompt, openai_api_key = Sys.getenv(\"OPENAI_API_KEY\"), messages = NULL) {\n if (is.null(messages)) {\n messages <- list(list(role = \"user\", content = prompt))\n }\n body <- list(\n model = \"gpt-3.5-turbo\",\n messages = messages\n )\n response <- POST(\n url = \"https://api.openai.com/v1/chat/completions\",\n add_headers(Authorization = paste(\"Bearer\", openai_api_key)),\n content_type_json(),\n body = jsonlite::toJSON(body, auto_unbox = TRUE)\n )\n if (response$status_code != 200) {\n stop(content(response, \"text\", encoding = \"UTF-8\"))\n }\n content <- jsonlite::fromJSON(content(response, \"text\", encoding = \"UTF-8\"))\n return(content$choices[[1]]$message$content)\n}"}}