# Introduction to openaiRtools

## Introduction

`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.

## Installation

    # Install from GitHub
    install.packages("remotes")
    remotes::install_github("xiaoluolorn/openaiRtools")

## Quick Start

### Setup

    library(openaiRtools)

    # Method 1: Set API key in environment (recommended)
    Sys.setenv(OPENAI_API_KEY = "your-api-key-here")
    client <- OpenAI$new()

    # Method 2: Pass API key directly
    client <- OpenAI$new(api_key = "your-api-key-here")

### Chat Completions

    # 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
    )

### Embeddings

    # Create embeddings
    response <- client$embeddings$create(
      input = "The quick brown fox jumps over the lazy dog",
      model = "text-embedding-ada-002"
    )

    # Access embedding vector
    embedding <- response$data[[1]]$embedding
    cat("Embedding dimension:", length(embedding))

### Images (DALL-E)

    # Generate image
    response <- client$images$create(
      prompt = "A cute baby sea otter in a spacesuit, digital art",
      model = "dall-e-3",
      size = "1024x1024",
      quality = "hd"
    )

    # Get image URL
    cat("Image URL:", response$data[[1]]$url)

### Audio

    # 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")

## Key Features

### 1. Full API Compatibility

`openaiRtools` implements all major OpenAI API endpoints:

- Chat Completions: GPT-4, GPT-3.5-Turbo, and more
- Embeddings: Text embedding models
- Images: DALL-E 3 and DALL-E 2
- Audio: Whisper transcriptions, translations, and TTS
- Models: List and retrieve model information
- Fine-tuning: Create and manage fine-tuning jobs

### 2. Python SDK Interface

The API design closely mirrors the Python SDK:

    # Python:
    # client.chat.completions.create(...)

    # R:
    client$chat$completions$create(...)

### 3. Convenience Functions

For simple use cases, use convenience functions:

    response <- create_chat_completion(
      messages = list(list(role = "user", content = "Hello")),
      model = "gpt-3.5-turbo"
    )

### 4. Error Handling

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")
      }
    )

## Configuration

### Environment Variables

- `OPENAI_API_KEY`: Your OpenAI API key (required)
- `OPENAI_ORG_ID`: Organization ID (optional)
- `OPENAI_PROJECT_ID`: Project ID (optional)

### Client Options

    client <- OpenAI$new(
      api_key = "your-key",
      base_url = "https://api.openai.com/v1",
      organization = "org-123",
      project = "proj-456",
      timeout = 600
    )

## Next Steps

- See `vignette("quickstart")` for more examples
- Read `vignette("function-calling")` for advanced function calling
- Check `vignette("error-handling")` for detailed error handling guide
- Visit the GitHub repository for complete API details