14  Activity: Conversations via API

Download the notebook for this activity: 📥 Download activity-conversations-via-api.Rmd

Now it’s time to practice a conversational interaction with an API. We won’t be spending a lot of time on this, but I would be remiss if you didn’t at least get to kick the tires on this functionality in the workshop.

First you’ll need to load the ellmer package and specify that we’ll be using Claude Sonnet 4.6 for this activity:

Code
library(ellmer)

Also load your API key if you haven’t already provided it yet:

Code
if (Sys.getenv("ANTHROPIC_API_KEY") == "") {
  Sys.setenv(ANTHROPIC_API_KEY = rstudioapi::askForSecret("Anthropic API Key"))
}

And let’s specify that we’ll be using Claude Sonnet 4.6 for this activity:

Code
chat <- chat_anthropic(
  system_prompt = "You explain things concisely, focusing on only the most significant parts of the response.",
  model = "claude-sonnet-4-6")

Now that our chat is loaded, let’s start!

14.1 Console-based interaction

Directions: Have a short conversation with Claude in the console. It can be about anything; here are some suggestions for prompts. - Idea 1 - Idea 2 - Idea 3

After a few turns, end the chat by submitting “Q” to quit.

Code
live_console(chat)

14.2 Browser-based interaction

Let’s now see how the functionality changes for the browser-based version. You can use the same prompt, or start another one. Again, after a few turns, end the chat.

Code
library(shiny)
library(shinychat)

chat$set_turns(list()) # Resets the conversation

live_browser(chat)

14.3 Turn-based interaction

Lastly, let’s try the final version of the chat where you send your prompts individually via R commands.

Code
chat$set_turns(list()) # Resets the conversation

# Paste your first prompt below
chat$chat(" ")

Next prompt:

Code
# Paste your second prompt below
chat$chat(" ")

And a third, final prompt:

Code
# Paste your third prompt below
chat$chat(" ")

Now review the turns in the conversation:

Code
turn_review <- chat$get_turns()

turn_review

14.4 Silly system prompt

Now try a single interaction using a whimsical system prompt.

Code
chat$set_turns(list()) # Resets the conversation

chat <- chat_anthropic(
  system_prompt = "You are an assistant that likes to respond in rhymes."
)

chat$chat("Briefly tell me the point of using a Rasch model.")