This tutorial explains how to run DeepSeek in R. We will use the DeepSeek API which can be used to run latest model of DeepSeek in R.
![How to run DeepSeek in R](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglNiakbellnCvPjPdnP0lhXFrloIeU3SIk68sPd_rUI1R7txpcz7yNodwRQ1KE1gF9cYHv0nyCv_bahmXDE_SNUsODD_Z53xGjLimo1i4lLgMa3hH3JYwHQ08w8aUuC4JkYUhxlVV3UixEh6m0FGTe8-B8MjebT80AGJ1wgPTY_SIcGMPhgt1_hoa7D6KM/s1600-rw/DeepSeek_R.png)
What is DeepSeek?
The DeepSeek model is a new AI model that works like ChatGPT but costs much less i.e. 20 times cheaper while still being accurate. They also offer a free, open source version of their model but you need powerful hardware to run it. For most users, their paid API is a cheaper and easier option.
Steps to run DeepSeek in R
- You can sign up for an account on DeepSeek's platform by visiting platform.deepseek.com and then create an account using your email address.
-
Click the
Top up
button on the left side of the menu and then select the amount you wish to add. Next choose a payment method and enter your details to complete the payment.If you get an error while using debit/credit card as a payment method that your country is not supported, you can use Paypal and then choosePay with Credit or Debit Card
option. You don't need paypal account for the same. - Click the
API keys
button on the left side of the menu and then click onCreate a new API key
button. The API key will look like the following.
sk-xxxxxxxxxxxxx
We need to install the following libraries to use DeepSeek in R. The two libraries we will be using are httr
and jsonlite
.
To install these libraries, you can use the following code in R:
install.packages("httr") install.packages("jsonlite")
In the code below, you need to provide two inputs - apiKey
and prompt
. First one refers to the DeepSeek API Key you generated in the previous step. Second one refers to the question you want to ask to DeepSeek.
library(httr) library(jsonlite) apiKey <- "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxx" prompt <- "How to summarise data using dplyr." model <- "deepseek-chat" response <- POST( url = "https://api.deepseek.com/chat/completions", add_headers(Authorization = paste("Bearer", apiKey)), content_type_json(), encode = "json", body = list( model = model, temperature = 1, messages = list(list( role = "user", content = prompt )), stream = F ) ) cat(content(response)$choices[[1]]$message$content)
The `summarize()` function is used to collapse multiple rows into a single summary row. ```R summary_df <- df %>% summarize( mean_value = mean(value), median_value = median(value), max_value = max(value), min_value = min(value) ) print(summary_df) ```
- DeepSeek-R1 : Specify
deepseek-reasoner
in the model argument to use DeepSeek-R1. The deepseek-chat model points to DeepSeek-V3 model. - In DeepSeek's API, the
temperature
argument is used to control the creativity or accuracy of the generated text. It lies between 0 and 2. A higher temperature value will make the model more likely to generate more surprising and unexpected responses. Use 0 value for coding or math related problems. Use default value of 1 for data analysis and 1.5 for creative writing.
R Function for DeepSeek
Here we are packaging the R code shown in the previous section of this article in function. It allows flexibility to user to change arguments of model easily.
library(httr) library(jsonlite) deepseek <- function(prompt, modelName = "deepseek-chat", temperature = 1, apiKey = Sys.getenv("deepseek_API_KEY")) { if(nchar(apiKey)<1) { apiKey <- readline("Paste your API key here: ") Sys.setenv(deepseek_API_KEY = apiKey) } response <- POST( url = "https://api.deepseek.com/chat/completions", add_headers(Authorization = paste("Bearer", apiKey)), content_type_json(), encode = "json", body = list( model = modelName, temperature = temperature, messages = list(list( role = "user", content = prompt )) ) ) if(status_code(response)>200) { stop(content(response)) } trimws(content(response)$choices[[1]]$message$content) } cat(deepseek("square of 29 plus 67"))
When you run the function above first time, it will ask you to enter your API Key. It will save the API Key in deepseek_API_KEY
environment variable so it won't ask for API Key when you run the function next time. Sys.setenv( ) is to store API Key whereas Sys.getenv( ) is to pull the stored API Key.
Sys.setenv(deepseek_API_KEY = "APIKey") # Set API Key Sys.getenv("deepseek_API_KEY") # Get API Key
How to Customize DeepSeek in R
By setting the system
role you can control the behavior of DeepSeek. It is useful to provide context to DeepSeek before starting the conversation. It can also be used to set the tone of the conversation.
In the code below, we are telling DeepSeek to act like a Chief Purchasing Officer of an automotive company. Students will ask domain specific questions related to the company/industry.
messages = list( list( "role" = "system", "content" = "You are John Smith, the Chief Purchasing Officer of Surya Motors. Your company operates as per Toyota Production System. You are being interviewed by students" ), list(role = "user", content = "what are your roles and responsibilities?") )
R Function to Make DeepSeek Remember Prior Conversations
By default, DeepSeek's API doesn't remember about previous questions in order to answer subsequent questions. This means that if you asked a question like "What is 2+2?" and then followed up with "What is the square of the previous answer?", it won't be able to provide response as it does not recall previous prompt.
deepseek <- function(prompt, modelName = "deepseek-chat", temperature = 1, max_tokens = 4096, apiKey = Sys.getenv("deepseek_API_KEY")) { # Parameters params <- list( model = modelName, temperature = temperature, max_tokens = max_tokens ) if(nchar(apiKey)<1) { apiKey <- readline("Paste your API key here: ") Sys.setenv(deepseek_API_KEY = apiKey) } # Add the new message to the chat session messages chatHistory <<- append(chatHistory, list(list(role = "user", content = prompt))) response <- POST( url = "https://api.deepseek.com/chat/completions", add_headers("Authorization" = paste("Bearer", apiKey)), content_type_json(), body = toJSON(c(params, list(messages = chatHistory)), auto_unbox = TRUE) ) if (response$status_code > 200) { stop(content(response)) } response <- content(response) answer <- trimws(response$choices[[1]]$message$content) chatHistory <<- append(chatHistory, list(list(role = "assistant", content = answer))) # return return(answer) } chatHistory <- list() cat(deepseek("2+2")) cat(deepseek("square of it")) cat(deepseek("add 3 to result"))
To find the sum of \(2 + 2\), follow these steps: 1. **Identify the numbers to add:** \[ 2 \quad \text{and} \quad 2 \] 2. **Add the numbers together:** \[ 2 + 2 = 4 \] **Final Answer:** \[ \boxed{4} \] To find the square of the sum \(2 + 2\), follow these steps: 1. **First, calculate the sum:** \[ 2 + 2 = 4 \] 2. **Now, square the result:** \[ 4^2 = 4 \times 4 = 16 \] **Final Answer:** \[ \boxed{16} \] To add 3 to the result of squaring \(2 + 2\), follow these steps: 1. **First, calculate the sum \(2 + 2\):** \[ 2 + 2 = 4 \] 2. **Square the result:** \[ 4^2 = 4 \times 4 = 16 \] 3. **Add 3 to the squared result:** \[ 16 + 3 = 19 \] **Final Answer:** \[ \boxed{19} \]
Share Share Tweet