openaiRtools is a complete R implementation of the
OpenAI Python SDK, providing full compatibility with the OpenAI API.
This package allows R users to access all OpenAI services including Chat
Completions, Embeddings, Images (DALL-E), Audio (Whisper and TTS),
Models, and Fine-tuning.
# Basic chat completion
response <- client$chat$completions$create(
messages = list(
list(role = "user", content = "Hello, how are you?")
),
model = "gpt-4"
)
cat(response$choices[[1]]$message$content)
# With parameters
response <- client$chat$completions$create(
messages = list(
list(role = "system", content = "You are a helpful assistant."),
list(role = "user", content = "What is R?")
),
model = "gpt-4",
temperature = 0.7,
max_tokens = 200
)# Transcribe audio
transcription <- client$audio$transcriptions$create(
file = "recording.mp3",
model = "whisper-1"
)
cat("Transcription:", transcription$text)
# Text-to-speech
audio_data <- client$audio$speech$create(
input = "Hello, this is a test of text to speech.",
model = "tts-1",
voice = "alloy"
)
# Save to file
writeBin(audio_data, "speech.mp3")openaiRtools implements all major OpenAI API
endpoints:
The API design closely mirrors the Python SDK:
For simple use cases, use convenience functions:
Comprehensive error handling with specific error classes:
tryCatch(
{
response <- client$chat$completions$create(
messages = list(list(role = "user", content = "Test")),
model = "gpt-4"
)
},
openai_api_error = function(e) {
cat("API Error:", e$message, "\n")
cat("Status Code:", e$status_code, "\n")
},
openai_connection_error = function(e) {
cat("Connection Error:", e$message, "\n")
},
error = function(e) {
cat("General Error:", e$message, "\n")
}
)OPENAI_API_KEY: Your OpenAI API key (required)OPENAI_ORG_ID: Organization ID (optional)OPENAI_PROJECT_ID: Project ID (optional)vignette("quickstart") for more examplesvignette("function-calling") for advanced function
callingvignette("error-handling") for detailed error
handling guide