---
title: "Introduction to ChatGTP Integration in RStudio"
author: "Abby Muricho Onencan"
session: 'Session One: Setup and Package air'
output:
  word_document: default
  html_document:
    df_print: paged
  pdf_document: default
editor_options:
  markdown:
    wrap: 72
---

## Session One: Setup and Packages "askgpt" and "air"

> ### 1. OPENAI CHAT GPT SETUP

#### *Step 1: Obtain API Key*

Obtain an API key from OpenAI at [<https://openai.com/api/%5D>. Click on
"API keys" under "Manage Account" to create a new key.

#### *Step 2: Load Necessary Libraries:*

```{r}
library(httr)       # library(httr) for making HTTP requests
library(jsonlite)   # library(jsonlite) to load a JSON parser and Generator
```

#### *Step 3: Define your OpenAI API key and request body:*

1.  Define your OpenAI AP
2.  Define request body
3.  Choose a model
4.  Define the test message
5.  Set the maximum tokens
6.  Set the temperature

```{r}
open_ai_key <- "YOUR_API-KEY"
  request_body <- list(
    model = "gpt-3.5-turbo-0125",
    messages = list(
      list(role = "user", content = "Say this is a test")
    ),
    max_tokens = 50,
    temperature = 0.7
  )
```

#### *Step 4: Test request completion:*

```{r}
# Send the POST request to OpenAI
response <- POST(
  url = "https://api.openai.com/v1/chat/completions",
  add_headers(
    "Content_Type" = "application/json",
    "Authorization" = paste("Bearer", open_ai_key)
  ),
  body = request_body,
  encode = "json"
)
  
      
# Extract and print the response
response_content <- content(response, encoding = "UTF-8")
print(response_content)
```

*If you encounter error:*

1.  Verify proper API key
2.  Check monthly API limit from OpenAI
3.  Ensure you're within the API limit
4.  Confirm API key access to the desired model

> ### 2. PACKAGE ASKGPT

-   Created by Johannes Gruber, the askgpt package is [available on
    CRAN](https://cran.r-project.org/web/packages/askgpt/index.html).

-   New to R? Confused by tutorial code or error messages? Use askgpt!
    [More
    information](https://github.com/JBGruber/askgpt?tab=readme-ov-file#usage)

-   Users can utilize the **chat_api()** function to set OpenAI API
    parameters.

-   It's like R's ChatGPT, offering help on errors and providing a handy
    RStudio addin for annotating code.

-   The package offers a general **askgpt()** function for queries.

-   Also there are coding-specific functions like **annotate_code()**,
    **explain_code()**, and **test_function()**.

```{r}
 library(askgpt)  # library(askgpt) for Asking GPT About R Stuff
```

#### 1. The most important setting, however, is askgpt_config

```{r}
# options(askgpt_config = "I'm 8 years old, please explain things easily")
# askgpt("What is a function in R programming?")
```

#### 2. Get to know each other:

```{r}
# askgpt("who are you?")
```

#### 3. Login help:

```{r}
# askgpt("How do I login to chatgpt?")
```

#### 4. You are new to Rstudio and have no idea where to start:

```{r}
# askgpt("I have no idea how to use Rstudio, help")
```

#### 5. Remind chatGPT that you are an 8 year old:

```{r}
# askgpt_config = "I'm 8 years old, please explain things easily"

# askgpt("Please explain for an 8 year old")
```

#### 6. Knit problems with askgpt:

```{r}
# askgpt("do you know why I cannot knit when I am using askgpt?")
```

#### 7. Ask a coding question and save as a variable:

`askgpt`'s default is to store the results of your query as an object
and they can be saved as a variable (linechart_instructions \<-).

```{r}
# askgpt("Create a line graph with multiple lines representing different groups (old, young, infants), use the provided sample data and ggplot2 library in R. Finally, print the line graph." )
```

*Check if the askgpt solution works (the results may be different
eveytime you run the prompt)*

```{r}
# Create sample data
set.seed(123)
data <- data.frame(
age = rep(c("old", "young", "infants"), each = 10),
value = rnorm(30),
time = rep(1:10, 3)
)

# Load the ggplot2 library
library(ggplot2)

# Create a line graph with multiple lines representing different groups
ggplot(data, aes(x = time, y = value, color = age, linetype = age)) +
geom_line() +
scale_color_manual(values = c("old" = "blue", "young" = "red", "infants" = "purple")) +
scale_linetype_manual(values = c("old" = "solid", "young" = "dashed", "infants" = "dotted")) +
labs(title = "Line Graph with Multiple Lines",
x = "Time",
y = "Value")
```

#### 8. Annotate_code() function

```{r}
# askgpt("give an example when I can use annotate_code function and explain why I need it")
```

#### 9. Explain_code() function

```{r}
# askgpt("give an example when I can use explain_code function and explain why I need it")
```

#### 10. Test_function()

```{r}
# askgpt("give an example when I can use test_function() and explain why I need it")
```

#### 11. Askgpt prompts:

```{r}
# askgpt("list a number of askgpt prompts used by r programmers" )
```

*NB: These prompts are more conversational and answering the question
**WHY** and **WHAT** - barely the question **HOW,** in relation to your
specific dataset, so you need another package if you are more interested
with HOW R programming prompts.*

> ### 3. PACKAGE "AIR"

-   Created by **Professor Soumya Ray** from the College of Technology
    Management at National Tsing Hua University in Taiwan. It is
    [available on
    CRAN](https://cran.r-project.org/web/packages/air/index.html).
-   Designed exclusively for R-related queries (doesn't support other
    programming languages).
-   The air R package provides R users with a chat-like feature akin to
    GitHub Copilot.
-   Answers appear in your R console, not in your script unless you use
    **R Notebook**.
-   The air package, available on CRAN, provides setup instructions on
    its [GitHub README page](https://github.com/soumyaray/air).
-   Use **air::set_key()** as asecure method for storing OpenAI keys
    (via a pop-up window)
-   Use **set_model()** to choose models other than the default gpt-4.
-   It offers two functions: **howto()** and **whatis().**

*Make sure you define your OpenAI API key and request body before using
"air"*

*First things first: Load Library "air"*

```{r}
library(air)    # An AI Assistant to Write and Undestand R Code
```

#### 1. Bar chart:howto()

*You must connect an OpenAI API key before using the howto() function.*

howto("Create a bar chart in R where the bars are colored (steel blue,
green, orange and yellow)and the bars are ordered by descending Y value
and print it")

```{r}
howto("Create a bar chart in R where the bars are colored (steel blue, green, 
      orange and yellow)and the bars are ordered by descending Y value and 
      print it")
```

*Check if the askgpt solution works (the results may be different
everytime you run the prompt)*

```{r}
library(ggplot2)
data <- data.frame(
  category = c("A", "B", "C", "D"),
  value = c(10, 8, 6, 4),
  color = c("steelblue", "green", "orange", "yellow")
)
data <- data[order(-data$value), ]

ggplot(data, aes(x = category, y = value, fill = color)) + 
  geom_bar(stat = "identity") + 
  theme_minimal()
```

#### 2. Line <graph:howto>()

howto("Create a line graph in R with multiple lines representing
different groups (old, young, infants), each with different colours and
style. Print the results as output in R Notebook" )

```{r}
howto("Create a line graph in R with multiple lines representing different 
      groups (old, young, infants), each with different colours and style. 
      Print the results as output in R Notebook" )
```

*Check if the askgpt solution works (the results may be different
everytime you run the prompt)*

```{r}
# Sample data 
set.seed(123)
df <- data.frame(
  age = rep(1:10, 3),
  group = rep(c("old", "young", "infants"), each = 10),
  value = c(rnorm(10, 20, 5), rnorm(10, 25, 5), rnorm(10, 15, 3))
)

# Load required library
library(ggplot2)

# Line plot
ggplot(df, aes(x = age, y = value, color = group, linetype = group)) +
  geom_line() +
  scale_color_manual(values = c("red", "blue", "purple")) +
  scale_linetype_manual(values = c("solid", "dashed", "dotted"))
```

#### 3. Scatter plot:howto()

howto("Produce a scatter plot in R with customized point shapes and
colors based on a categorical variable, name the variables (cats, dogs,
horses, cows) and produce a key. Print the results as output in R
Markdown.")

```{r}
howto("Produce a scatter plot in R with customized point shapes and colors 
      based on a categorical variable, name the variables (cats, dogs, horses, 
      cows) and produce a key. Print the results as output in R Markdown.")
```

*Check if the askgpt solution works (the results may be different
everytime you run the prompt)*

```{r}
# Sample data
animals <- data.frame(
  x = rnorm(100),
  y = rnorm(100),
  type = sample(c("cats", "dogs", "horses", "cows"), 100, replace = TRUE)
)

# Scatter plot
plot(animals$x, animals$y, col = ifelse(animals$type == "cats", "red",
                  ifelse(animals$type == "dogs", "blue",
                  ifelse(animals$type == "horses", "green", "yellow"))),
     pch = ifelse(animals$type == "cats", 1,
            ifelse(animals$type == "dogs", 4,
            ifelse(animals$type == "horses", 5, 8))),
     main = "Animal Scatter Plot",
     xlab = "X-axis",
     ylab = "Y-axis")
legend("topright", legend = unique(animals$type), pch = c(1, 4, 5, 8),
       col = c("red", "blue", "green", "yellow"), title = "Types")
```

#### 4. Package "air":whatis(ggplot2 package)

```{r}
whatis("ggplot2 package")
```

#### 5. Package "air":whatis(RTutor gpt library)

```{r}
whatis("RTutor gpt library")
```

#### 6. Package "air":whatis(TheOpenAir package)

```{r}
whatis("TheOpenAir package")
```

#### 7. Package "air":whatis(gptchatteR library for chatgpt)

```{r}
whatis("gptchatteR library for chatgpt")
```

#### 8. Package "air":whatis (ask_gpt)

```{r}
whatis ("ask_gpt library available at https://github.com/cran/askgpt")
```

#### 9. Package "air":whatis(gpttools)

```{r}
whatis("gpttools from JamesHWade/gpttools GitHub repo or R Universe")
```

#### 10. Package "air":whatis(gtpchatter)

```{r}
whatis("the advantage of the advantage of the gtpchatter downloadable 
       from github: isinaltinkaya/gptchatteR")
```

#### 11. Package "air":whatis(best ChatGTP Temperature)

whatis("The OpenAI API incorporates a hyperparameter known as
temperature that affects the computation of token probabilities when
generating output through the large language model. The temperature
value ranges from 0 to 2, with lower values indicating greater
determinism and higher values indicating more randomness.What is the
best OpenAI temperature for R programming")

```{r}
whatis("The OpenAI API incorporates a hyperparameter known as temperature that 
       affects the computation of token probabilities when generating output 
       through the large language model. The temperature value ranges 
       from 0 to 2, with lower values indicating greater determinism and 
       higher values indicating more randomness.What is the best OpenAI 
       temperature for R programming")
```
