Coder Social home page Coder Social logo

askgpt's Introduction

askgpt

Lifecycle: stable R-CMD-check Codecov test coverage CRAN status CRAN_Download_Badge

You’re new to R? You don’t quite understand the code you copied from that tutorial? You get error messages that make no sense to you? Don’t worry, just askgpt!

askgpt is basically ChatGPT but from R (technically, it sends prompts to OpenAI’s API directly from R). It also has some additional functionality:

  • Prompt “What is wrong with my last command?” (or “help!”) to get help on the last error R emitted
  • Use the RStudio addin to comment, annotate or explain highlighted code

See more under Usage.

Installation

You can install release version of askgpt like so:

install.packages("askgpt")

You can install the development version of askgpt like so:

remotes::install_github("JBGruber/askgpt")

Log In

You can log into OpenAI’s API running the dedicated login() function or just ask something with askgpt():

library(askgpt)
login()
#> ℹ It looks like you have not provided an API key yet. Let me guide you through the process:
#>   1. Go to <https://platform.openai.com/account/api-keys>
#>   2. (Log into your account if you haven't done so yet)
#>   3. On the site, click the button + Create new secret key
#>   to create an API key
#>   4. Copy this key into R/RStudio
Copy the API key from OpenAI's website

Copy the API key from OpenAI’s website

And paste it into RStudio

And paste it into RStudio

You will not need to do this again after the first time. (Technical detail: This will store an encrypted version of your key in the directory returned by rappdirs::user_cache_dir("askgpt").) If your old API key does not work any more, you can store a new one with: login(force_refresh = TRUE).

Usage

To enable error logging (which you need if you want askgpt to explain errors to you) first run:

log_init()

After this, the key phrase “What is wrong with my last command?” (or just “help!”) will make askgpt look up your last command and error message and return some help for you. The other important key phrase is “Can you elaborate on that?” (or just “What?”), which will elaborate on the previous answer. You can ask basically any question you want though:

examples.mp4
some examples

Configure

You can configure how askgpt makes that start with askgpt_*. For example, to use a different model to use in askgpt() use options(askgpt_chat_model = "gpt-3.5-turbo-0301") (or options(askgpt_chat_model = "gpt-4") if you have beta access to the newer model). If you use the completions instead of the chat API (chat = FALSE in askgpt()) use options(askgpt_completions_model = "text-curie-001"). It does not matter if the API parameter is listed in the function or not. All are used. See the complete list here and here.

The most important setting, however, is askgpt_config. This can be used to configure the chat using plain English:

options(askgpt_config = "I'm 8 years old, please explain things easily")
askgpt("What is an R function?")
#> 
#> ── Answer ──────────────────────────────────────────────────────────────────────
#> An R function is like giving your friend a set of instructions to perform a
#> particular task. In R programming, a function is a set of instructions or steps
#> that is given a name, and when you call that name, the function will perform
#> those instructions. A function can take information or inputs, do something
#> with those inputs (like adding or subtracting), and then give the result back
#> as output.
#> 
#> For example, think about giving your friend the instructions to make a peanut
#> butter sandwich. The instructions might be:
#> 
#> 1. Take two slices of bread 2. Spread peanut butter on one slice 3. Spread
#> jelly on the other slice 4. Put the two slices together
#> 
#> In R, a function might take a number (like 5) and add 1 to it, and then return
#> the result (which would be 6).
#> 
#> Functions in R are used to make code easier to use, understand, and reuse. They
#> can also help programmers write complex and efficient programs.

askgpt's People

Contributors

jbgruber avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

askgpt's Issues

Answers containing R Markdown systax are evaluated

If code is returned in a R Markdown syntax, the underlying cli::cli_inform(c(trimws(out))) evaluates it, since it is similar to glue notation.

Example:

out <- "As an R tutor, I believe that it's important for you to learn and practice coding on your own. Therefore, I'll guide you through the process of writing a for loop to read in CSV files:\n\n1. Set your working directory to the folder containing the CSV files using the `setwd()` function. For example, `setwd(\"~/Documents/csv_folder\")`.\n\n2. Use the `list.files()` function to get a list of all the CSV files in the folder. For example, `csv_files <- list.files(path = \".\", pattern = \".csv\")`.\n\n3. Use a for loop to iterate over the files in the `csv_files` vector. For example:\n\n```\nfor (i in seq_along(csv_files)) {\n  # Read in the CSV file\n  csv_data <- read.csv(csv_files[i])\n  \n  # Do something with the data, if desired\n  ...\n}\n```\n\nIn this code, `seq_along()` is used to create a sequence of numbers from 1 to the length of the `csv_files` vector. The for loop iterates over these numbers and uses them to index into the `csv_files` vector. The `read.csv()` function is then used to read in each file one at a time.\n\nNote that this is just one possible approach to reading in CSV files using a for loop, and there are many variations and options you could use depending on your specific situation. As an R tutor, I encourage you to experiment with different approaches and think critically about which methods are most appropriate for your tasks."
cli::cli_inform(c(trimws(out)))
#> Error in "lapply(text, glue_cmd, .envir = .envir)": ! Could not evaluate cli `{}` expression: ` # Read in the CS…`.
#> Caused by error in `read.table(file = file, header = header, sep = sep, quote = quote, …`:
#> ! object 'csv_files' not found

Created on 2023-03-15 with reprex v2.0.2

Everything in this answer between { and } is evaluated.

HTTP 401 Unauthorized

Hi,

if I run the command:
askgpt("What is an R function?")

I get the following error messages:
Error:is thinking ⠇
! ! in callr subprocess.
Caused by error in resp_abort(resp, error_body(req, resp)):
! HTTP 401 Unauthorized.
Run rlang::last_error() to see where the error occurred.
✖ GPT is thinking ⠇ [1.6s]

I partly understand the problem but I do not know how to solve it in R. Btw I have full administrative rights on the PC and a working internet connection. Using ChatGPT in the explorer works fine as well.

Many thanks in advance!
Jörg

No output generated with `askgpt()`

Running askgpt() with the default arguments does not output anything to the screen:

> askgpt("Tell me about the askgpt R package")
✔ GPT is thinking ⠧ [17.5s]
>

However the answer is available using response_history():

> response_history()[1] |> cat()
Askgpt is an R package that provides an easy-to-use interface for OpenAI's GPT-3 API. GPT-3 (Generative Pre-trained Transformer 3) is a powerful language generation model developed by OpenAI, which can be used to generate human-like text in a wide variety of formats.

The askgpt R package allows users to easily generate text using GPT-3 from within the R environment, making it easy to incorporate natural language generation into R-based projects. The package provides an R wrapper around the GPT-3 API, which allows users to access the full range of GPT-3 functions, including text completion, text classification, and text translation.

To use askgpt, users must first sign up for an OpenAI API key and create an account with OpenAI. Once they have an account, they can install the askgpt package in R using the R console or Rstudio, and they can begin generating text using the GPT-3 API by providing an API key and a text prompt. The package also provides functions for fine-tuning the GPT-3 model, controlling the output length and format, and filtering the output to remove unwanted content.

The askgpt R package is a powerful tool for natural language generation and can be used in a wide variety of applications, including data analysis, machine learning, and text mining. It provides an intuitive and user-friendly interface for accessing the GPT-3 API, making it easy for anyone to start generating high-quality human-like text in R.

If there's any missing step in the configuration, I don't know what it is.

> sessionInfo()
R version 4.3.0 (2023-04-21)
Platform: x86_64-apple-darwin20 (64-bit)
Running under: macOS Ventura 13.2.1

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib 
LAPACK: /Library/Frameworks/R.framework/Versions/4.3-x86_64/Resources/lib/libRlapack.dylib;  LAPACK version 3.11.0

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

time zone: Europe/Warsaw
tzcode source: internal

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] askgpt_0.1.1

loaded via a namespace (and not attached):
 [1] jsonlite_1.8.4    dplyr_1.1.2       compiler_4.3.0    tidyselect_1.2.0 
 [5] reprex_2.0.2      clipr_0.8.0       assertthat_0.2.1  callr_3.7.3      
 [9] yaml_2.3.7        fastmap_1.1.1     R6_2.5.1          generics_0.1.3   
[13] curl_5.0.0        knitr_1.43        httr2_0.2.3       tibble_3.2.1     
[17] openssl_2.0.6     R.cache_0.16.0    pillar_1.9.0      R.utils_2.12.2   
[21] rlang_1.1.1       utf8_1.2.3        xfun_0.39         fs_1.6.2         
[25] cli_3.6.1         withr_2.5.0       magrittr_2.0.3    ps_1.7.5         
[29] digest_0.6.31     processx_3.8.1    rstudioapi_0.14   keyring_1.3.1    
[33] rappdirs_0.3.3    askpass_1.1       lifecycle_1.0.3   R.methodsS3_1.8.2
[37] R.oo_1.25.0       vctrs_0.6.2       evaluate_0.21     glue_1.6.2       
[41] styler_1.10.0     sessioninfo_1.2.2 fansi_1.0.4       rmarkdown_2.22   
[45] purrr_1.0.1       htmltools_0.5.5   tools_4.3.0       pkgconfig_2.0.3  

Error running askgpt

I got an error when I try to use askgpt:

library(askgpt)
log_init()
askgpt("what is an R function")
Error:is thinking ⠦
! ! in callr subprocess.
Caused by error in resp_abort(resp, error_body(req, resp)):
! HTTP 429 Too Many Requests.
Run rlang::last_trace() to see where the error occurred.
✖ GPT is thinking ⠦ [3.1s]

Remove or fix streaming feature

I moved the option to stream a response to a fork since it is broken for the chat API and does not really do anything nice for the completions API. Originally, it looked like streaming the response would create a similar 'typing' effect like on the ChatGPT site. But once the API starts streaming, it just sends the whole reply very quickly. I (or someone who feels like it) could fix the feature at some point, but I think it makes more sense to just remove it.

Trying to annotate selected code

Getting the following output:

askgpt::annotate_code()
✔ GPT is thinking ⠧ [9.2s]
Warning message:
In file(loc, "ab") :
file("") only supports open = "w+" and open = "w+b": using the former

I am running on rstudio server

Can not make it work, keeps giving this error message.

remotes::install_github("JBGruber/askgpt")
#rappdirs::user_cache_dir("askgpt")
#login(force_refresh = TRUE)
library(askgpt)
askgpt("Can you explain how functions work in R?")

Error:is thinking
! ! in callr subprocess.
Caused by error:
! Timeout was reached: [api.openai.com] Connection timeout after 10010 ms
Backtrace:

  1. askgpt::askgpt("Can you explain how functions work in R?")
  2. rp$get_result()
  3. callr:::rp_get_result(self, private)
  4. callr:::get_result(out, private$options)
  5. throw(callr_remote_error(remerr, output), parent = fix_msg(remerr[[3]]))
    x GPT is thinking \ [12.5s]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.