| Title: | R Client for the 'OpenAI' API |
|---|---|
| Description: | Complete R implementation of OpenAI Python SDK. Provides full compatibility with OpenAI API including chat completions, embeddings, images, audio, fine-tuning, and model management. |
| Authors: | Chaoyang Luo [aut, cre] |
| Maintainer: | Chaoyang Luo <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.2.2 |
| Built: | 2026-06-05 08:01:16 UTC |
| Source: | https://github.com/xiaoluolorn/openairtools |
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and uploads one part of a multipart upload.
Call this repeatedly for each chunk of your file.
add_upload_part(upload_id, data)add_upload_part(upload_id, data)
upload_id |
Character. Required. The upload session ID returned
by |
data |
Raw. Required. The binary chunk to upload.
Read from file with |
An upload part object with $id — save all part IDs to use
in complete_upload().
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") chunk <- readBin("large_file.jsonl", "raw", n = 64 * 1024 * 1024) part <- add_upload_part(upload_id = upload$id, data = chunk) cat("Part ID:", part$id) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") chunk <- readBin("large_file.jsonl", "raw", n = 64 * 1024 * 1024) part <- add_upload_part(upload_id = upload$id, data = chunk) cat("Part ID:", part$id) ## End(Not run)
An Assistant is a configured AI entity with a model, instructions, and optional tools. It operates on ThreadsClient (conversations) by creating Runs that execute the assistant's logic.
Client for the OpenAI Assistants API v2 (Beta).
Assistants are AI agents that can use tools (code interpreter,
file search, custom functions) and maintain persistent state.
Access via client$assistants.
Create an assistant: client$assistants$create(model, instructions, tools)
Create a thread: client$threads$create()
Add a user message: client$threads$messages$create(thread_id, "user", "...")
Create a run: client$threads$runs$create(thread_id, assistant_id)
Poll the run until status is "completed"
Read the assistant's reply: client$threads$messages$list(thread_id)
new()
AssistantsClient$new(parent)
create()
AssistantsClient$create( model, name = NULL, description = NULL, instructions = NULL, tools = NULL, tool_resources = NULL, metadata = NULL, temperature = NULL, top_p = NULL, response_format = NULL )
list()
AssistantsClient$list(limit = NULL, order = NULL, after = NULL, before = NULL)
retrieve()
AssistantsClient$retrieve(assistant_id)
update()
AssistantsClient$update(assistant_id, ...)
delete()
AssistantsClient$delete(assistant_id)
clone()
The objects of this class are cloneable with this method.
AssistantsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Top-level client for the OpenAI Audio API, providing access to
transcription, translation, and text-to-speech services.
Access via client$audio.
$transcriptionsAudioTranscriptionsClient — Whisper speech-to-text
$translationsAudioTranslationsClient — Whisper audio translation to English
$speechSpeechClient — Text-to-speech (TTS)
new()
AudioClient$new(parent)
clone()
The objects of this class are cloneable with this method.
AudioClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Transcribes audio files to text using OpenAI's Whisper model.
Access via client$audio$transcriptions.
new()
AudioTranscriptionsClient$new(parent)
create()
AudioTranscriptionsClient$create( file, model = "whisper-1", language = NULL, prompt = NULL, response_format = NULL, temperature = NULL, timestamp_granularities = NULL )
clone()
The objects of this class are cloneable with this method.
AudioTranscriptionsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Translates audio from any supported language into English text using
Whisper. Access via client$audio$translations.
new()
AudioTranslationsClient$new(parent)
create()
AudioTranslationsClient$create( file, model = "whisper-1", prompt = NULL, response_format = NULL, temperature = NULL )
clone()
The objects of this class are cloneable with this method.
AudioTranslationsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
The Batch API accepts a JSONL file of requests, processes them within a 24-hour window, and returns the results in an output file. Suitable for: bulk embeddings, offline evaluation, large-scale text processing, or any task that does not require immediate results.
Client for the OpenAI Batch API. Process large volumes of API requests
asynchronously at 50% lower cost than synchronous calls.
Access via client$batch.
Create a JSONL file where each line is one API request (see format below)
Upload the file: client$files$create(file, purpose = "batch")
Create a batch: client$batch$create(input_file_id, endpoint)
Poll status: client$batch$retrieve(batch_id)
Download results: client$files$content(batch$output_file_id)
Each line in the input file must be:
{"custom_id": "req-1", "method": "POST",
"url": "/v1/chat/completions",
"body": {"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "Hello!"}]}}
new()
BatchClient$new(parent)
create()
BatchClient$create( input_file_id, endpoint, completion_window = "24h", metadata = NULL )
list()
BatchClient$list(after = NULL, limit = NULL)
retrieve()
BatchClient$retrieve(batch_id)
cancel()
BatchClient$cancel(batch_id)
clone()
The objects of this class are cloneable with this method.
BatchClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and cancels a batch job.
cancel_batch(batch_id)cancel_batch(batch_id)
batch_id |
Character. Required. The batch ID to cancel. |
A batch object with $status = "cancelling".
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- cancel_batch("batch_abc123") cat("Status:", result$status) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- cancel_batch("batch_abc123") cat("Status:", result$status) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and cancels a running or queued fine-tuning job.
cancel_fine_tuning_job(fine_tuning_job_id)cancel_fine_tuning_job(fine_tuning_job_id)
fine_tuning_job_id |
Character. Required. The job ID to cancel. |
The fine-tuning job object with $status = "cancelled".
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- cancel_fine_tuning_job("ftjob-abc123") cat("Status:", result$status) # "cancelled" ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- cancel_fine_tuning_job("ftjob-abc123") cat("Status:", result$status) # "cancelled" ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and cancels an in-progress response.
cancel_response(response_id)cancel_response(response_id)
response_id |
Character. Required. The response ID to cancel. |
The cancelled response object.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") cancel_response("resp_abc123") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") cancel_response("resp_abc123") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and cancels a running or queued run.
cancel_run(thread_id, run_id)cancel_run(thread_id, run_id)
thread_id |
Character. Required. The thread ID. |
run_id |
Character. Required. The run ID to cancel. |
A run object with $status = "cancelling".
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") cancel_run("thread_abc123", "run_abc123") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") cancel_run("thread_abc123", "run_abc123") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and cancels an in-progress multipart upload.
cancel_upload(upload_id)cancel_upload(upload_id)
upload_id |
Character. Required. The upload session ID to cancel. |
An upload object with $status = "cancelled".
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- cancel_upload("upload_abc123") cat("Status:", result$status) # "cancelled" ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- cancel_upload("upload_abc123") cat("Status:", result$status) # "cancelled" ## End(Not run)
Client for OpenAI Chat Completions API. Access via client$chat.
new()
ChatClient$new(parent)
clone()
The objects of this class are cloneable with this method.
ChatClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Provides methods to create, manage and retrieve chat completions.
Access via client$chat$completions.
new()
ChatCompletionsClient$new(parent)
create()
ChatCompletionsClient$create( messages, model = "gpt-3.5-turbo", frequency_penalty = NULL, logit_bias = NULL, logprobs = NULL, top_logprobs = NULL, max_tokens = NULL, max_completion_tokens = NULL, n = NULL, presence_penalty = NULL, response_format = NULL, seed = NULL, stop = NULL, stream = NULL, stream_options = NULL, temperature = NULL, top_p = NULL, tools = NULL, tool_choice = NULL, parallel_tool_calls = NULL, user = NULL, store = NULL, metadata = NULL, callback = NULL, ... )
retrieve()
ChatCompletionsClient$retrieve(completion_id)
update()
ChatCompletionsClient$update(completion_id, metadata = NULL)
list()
ChatCompletionsClient$list( model = NULL, after = NULL, limit = NULL, order = NULL, metadata = NULL )
delete()
ChatCompletionsClient$delete(completion_id)
clone()
The objects of this class are cloneable with this method.
ChatCompletionsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Lists messages from stored chat completions.
Access via client$chat$completions$messages.
new()
ChatCompletionsMessagesClient$new(parent)
list()
ChatCompletionsMessagesClient$list( completion_id, after = NULL, limit = NULL, order = NULL )
clone()
The objects of this class are cloneable with this method.
ChatCompletionsMessagesClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and finalizes a multipart upload.
Assembles all uploaded parts into a single file.
complete_upload(upload_id, part_ids, ...)complete_upload(upload_id, part_ids, ...)
upload_id |
Character. Required. The upload session ID. |
part_ids |
List of character strings. Required. Part IDs collected
from |
... |
Additional parameters such as |
A standard File object with $id that can be used in fine-tuning,
assistants, or batch API calls, just like a file from upload_file().
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # After uploading all parts, complete the upload: file_obj <- complete_upload( upload_id = upload$id, part_ids = list("part-001", "part-002", "part-003") ) cat("File ID:", file_obj$id) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # After uploading all parts, complete the upload: file_obj <- complete_upload( upload_id = upload$id, part_ids = list("part-001", "part-002", "part-003") ) cat("File ID:", file_obj$id) ## End(Not run)
Note: This is the legacy "instruct" style API. For most use cases,
use ChatCompletionsClient (client$chat$completions) instead.
The Completions API is suitable only for "gpt-3.5-turbo-instruct" and
"davinci-002". It takes a raw text prompt and returns a completion.
Client for the OpenAI Completions API (legacy text completion endpoint).
Access via client$completions.
new()
CompletionsClient$new(parent)
create()
CompletionsClient$create( prompt, model = "gpt-3.5-turbo-instruct", max_tokens = NULL, temperature = NULL, top_p = NULL, n = NULL, stream = NULL, logprobs = NULL, echo = NULL, stop = NULL, presence_penalty = NULL, frequency_penalty = NULL, best_of = NULL, logit_bias = NULL, user = NULL, callback = NULL )
clone()
The objects of this class are cloneable with this method.
CompletionsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$assistants$create().
create_assistant(model, ...)create_assistant(model, ...)
model |
Character. Required. Model ID to power the assistant
(e.g. |
... |
Additional parameters passed to AssistantsClient |
An assistant object with $id (save this for future use),
$name, $model, $instructions, and $tools.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") asst <- create_assistant( model = "gpt-4o", name = "Stats Helper", instructions = "You help with statistical analysis in R and Python.", tools = list(list(type = "code_interpreter")) ) cat("Created assistant ID:", asst$id) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") asst <- create_assistant( model = "gpt-4o", name = "Stats Helper", instructions = "You help with statistical analysis in R and Python.", tools = list(list(type = "code_interpreter")) ) cat("Created assistant ID:", asst$id) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$batch$create().
create_batch(input_file_id, endpoint, ...)create_batch(input_file_id, endpoint, ...)
input_file_id |
Character. Required. File ID of the uploaded
JSONL batch input file (uploaded with |
endpoint |
Character. Required. API endpoint for each request.
One of |
... |
Additional parameters passed to BatchClient |
A batch object with $id and $status.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") batch <- create_batch( input_file_id = "file-abc123", endpoint = "/v1/chat/completions" ) cat("Batch ID:", batch$id) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") batch <- create_batch( input_file_id = "file-abc123", endpoint = "/v1/chat/completions" ) cat("Batch ID:", batch$id) ## End(Not run)
A shortcut that automatically creates an OpenAI client from the
OPENAI_API_KEY environment variable and calls
client$chat$completions$create().
create_chat_completion(messages, model = "gpt-3.5-turbo", ...)create_chat_completion(messages, model = "gpt-3.5-turbo", ...)
messages |
Required. List of message objects. Each must have
|
model |
Character. Model ID. Default: |
... |
Additional parameters passed to
ChatCompletionsClient |
A chat completion list object. Key fields:
$choices[[1]]$message$content — The generated text
$usage$total_tokens — Total tokens consumed
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") response <- create_chat_completion( messages = list(list(role = "user", content = "What is machine learning?")), model = "gpt-4o" ) cat(response$choices[[1]]$message$content) # With extra parameters response <- create_chat_completion( messages = list(list(role = "user", content = "Write a poem")), model = "gpt-4o", temperature = 1.2, max_tokens = 200 ) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") response <- create_chat_completion( messages = list(list(role = "user", content = "What is machine learning?")), model = "gpt-4o" ) cat(response$choices[[1]]$message$content) # With extra parameters response <- create_chat_completion( messages = list(list(role = "user", content = "Write a poem")), model = "gpt-4o", temperature = 1.2, max_tokens = 200 ) ## End(Not run)
Note: This is the legacy Completions API. For most tasks, use
create_chat_completion() instead, which supports system prompts,
conversation history, and more capable models.
create_completion(prompt, model = "gpt-3.5-turbo-instruct", ...)create_completion(prompt, model = "gpt-3.5-turbo-instruct", ...)
prompt |
Character. Required. The text prompt to complete. |
model |
Character. Model ID. Only |
... |
Additional parameters passed to CompletionsClient |
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$completions$create().
A named list. Access the generated text via
$choices[[1]]$text.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Complete a sentence resp <- create_completion( prompt = "The most important assumption of OLS regression is", model = "gpt-3.5-turbo-instruct", max_tokens = 100 ) cat(resp$choices[[1]]$text) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Complete a sentence resp <- create_completion( prompt = "The most important assumption of OLS regression is", model = "gpt-3.5-turbo-instruct", max_tokens = 100 ) cat(resp$choices[[1]]$text) ## End(Not run)
Shortcut that automatically creates an OpenAI client and calls
client$embeddings$create(). The API key is read from the
OPENAI_API_KEY environment variable.
create_embedding(input, model = "text-embedding-ada-002", ...)create_embedding(input, model = "text-embedding-ada-002", ...)
input |
Required. A character string or list of strings to embed. |
model |
Character. Embedding model. Default: |
... |
Additional parameters passed to |
A named list with $data[[i]]$embedding containing the
numeric embedding vectors.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Single embedding resp <- create_embedding("Hello world", model = "text-embedding-3-small") vec <- unlist(resp$data[[1]]$embedding) cat("Vector length:", length(vec)) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Single embedding resp <- create_embedding("Hello world", model = "text-embedding-3-small") vec <- unlist(resp$data[[1]]$embedding) cat("Vector length:", length(vec)) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$fine_tuning$jobs$create().
create_fine_tuning_job(training_file, model = "gpt-3.5-turbo", ...)create_fine_tuning_job(training_file, model = "gpt-3.5-turbo", ...)
training_file |
Character. Required. File ID of the uploaded
training JSONL file (e.g. from |
model |
Character. Base model to fine-tune:
|
... |
Additional parameters passed to FineTuningJobsClient |
A fine-tuning job object with $id and $status.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") job <- create_fine_tuning_job( training_file = "file-abc123", model = "gpt-3.5-turbo", suffix = "my-assistant", hyperparameters = list(n_epochs = 3) ) cat("Job ID:", job$id) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") job <- create_fine_tuning_job( training_file = "file-abc123", model = "gpt-3.5-turbo", suffix = "my-assistant", hyperparameters = list(n_epochs = 3) ) cat("Job ID:", job$id) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$images$create().
create_image(prompt, model = "dall-e-3", ...)create_image(prompt, model = "dall-e-3", ...)
prompt |
Character. Required. Text description of the desired image. For DALL-E 3, up to 4000 characters. |
model |
Character. Image model: |
... |
Additional parameters passed to ImagesClient |
A list with $data[[1]]$url containing the image URL, and
$data[[1]]$revised_prompt with the prompt used by DALL-E 3.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Generate a standard image resp <- create_image("A futuristic chart showing economic data, neon style") cat(resp$data[[1]]$url) # HD landscape resp <- create_image( prompt = "A detailed map of global trade routes", model = "dall-e-3", size = "1792x1024", quality = "hd", style = "natural" ) cat(resp$data[[1]]$url) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Generate a standard image resp <- create_image("A futuristic chart showing economic data, neon style") cat(resp$data[[1]]$url) # HD landscape resp <- create_image( prompt = "A detailed map of global trade routes", model = "dall-e-3", size = "1792x1024", quality = "hd", style = "natural" ) cat(resp$data[[1]]$url) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$images$edit().
Edits a local PNG image based on a text prompt and optional mask.
create_image_edit(image, prompt, mask = NULL, ...)create_image_edit(image, prompt, mask = NULL, ...)
image |
Character. Required. Path to the local square PNG to edit (less than 4 MB). |
prompt |
Character. Required. Description of the desired edit. |
mask |
Character or NULL. Path to a mask PNG. Transparent pixels indicate which region to edit. Default: NULL (entire image). |
... |
Additional parameters passed to ImagesClient |
A list with $data containing the edited image object(s).
Access the URL via $data[[1]]$url.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") resp <- create_image_edit( image = "photo.png", prompt = "Add a mountain range in the background", mask = "sky_mask.png" ) cat(resp$data[[1]]$url) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") resp <- create_image_edit( image = "photo.png", prompt = "Add a mountain range in the background", mask = "sky_mask.png" ) cat(resp$data[[1]]$url) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$images$create_variation().
Generates one or more variations of an existing image.
create_image_variation(image, model = "dall-e-2", ...)create_image_variation(image, model = "dall-e-2", ...)
image |
Character. Required. Path to the local square PNG image (less than 4 MB). |
model |
Character. Currently only |
... |
Additional parameters passed to ImagesClient |
A list with $data containing the generated variation image(s).
Access the URL via $data[[1]]$url.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Generate 2 variations of your logo resp <- create_image_variation( image = "logo.png", n = 2, size = "512x512" ) cat(resp$data[[1]]$url) cat(resp$data[[2]]$url) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Generate 2 variations of your logo resp <- create_image_variation( image = "logo.png", n = 2, size = "512x512" ) cat(resp$data[[1]]$url) cat(resp$data[[2]]$url) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and adds a message to a thread.
create_message(thread_id, role, content, ...)create_message(thread_id, role, content, ...)
thread_id |
Character. Required. The thread ID. |
role |
Character. Required. |
content |
Character or list. Required. The message text, or a list of content parts for multimodal messages. |
... |
Additional parameters passed to MessagesClient |
A message object with $id and $content.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") msg <- create_message( thread_id = "thread_abc123", role = "user", content = "What is the difference between FE and RE estimators?" ) cat("Message ID:", msg$id) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") msg <- create_message( thread_id = "thread_abc123", role = "user", content = "What is the difference between FE and RE estimators?" ) cat("Message ID:", msg$id) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$moderations$create().
create_moderation(input, model = "omni-moderation-latest")create_moderation(input, model = "omni-moderation-latest")
input |
Required. A character string or list of strings to moderate.
Example: |
model |
Character. Moderation model to use:
|
This API is free and does not consume tokens. Use it to screen user-generated content before passing it to other APIs.
A list with $results — a list of result objects, one per input.
Each result has:
$flagged — Logical, TRUE if content violates policy
$categories — Named list of boolean flags per category
$category_scores — Named list of scores (0–1) per category
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Quick single-text check result <- create_moderation("I love everyone!") cat("Flagged:", result$results[[1]]$flagged) # FALSE # Screen multiple texts from user input texts <- list("normal message", "harmful content example") result <- create_moderation(texts) for (i in seq_along(result$results)) { cat("Text", i, "flagged:", result$results[[i]]$flagged, "\n") } ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Quick single-text check result <- create_moderation("I love everyone!") cat("Flagged:", result$results[[1]]$flagged) # FALSE # Screen multiple texts from user input texts <- list("normal message", "harmful content example") result <- create_moderation(texts) for (i in seq_along(result$results)) { cat("Text", i, "flagged:", result$results[[i]]$flagged, "\n") } ## End(Not run)
Convenience function that assembles a complete "user" message object
containing both text and one or more images. Automatically handles URL vs.
local file detection.
create_multimodal_message(text = NULL, images = NULL, detail = "auto")create_multimodal_message(text = NULL, images = NULL, detail = "auto")
text |
Character or |
images |
List of image sources. Each element can be:
Default: |
detail |
Character. Detail level applied to all images supplied
as strings. Ignored for pre-built content parts.
|
Pass the returned object (or a list of such objects) directly to
client$chat$completions$create(messages = ...).
A named list representing a "user" message:
list(
role = "user",
content = list(
list(type = "text", text = <text>),
list(type = "image_url", image_url = list(url = ..., detail = ...)),
...
)
)
image_from_url(), image_from_file(),
image_from_plot()
## Not run: library(openaiRtools) client <- OpenAI$new(api_key = "sk-xxxxxx") # --- URL image --- msg <- create_multimodal_message( text = "What is shown in this chart?", images = list("https://example.com/gdp_chart.png") ) response <- client$chat$completions$create(messages = list(msg), model = "gpt-4o") # --- Local file --- msg <- create_multimodal_message( text = "Identify any statistical issues in this residual plot.", images = list("output/resid_plot.png"), detail = "high" ) # --- Multiple images (compare two charts) --- msg <- create_multimodal_message( text = "Compare these two regression diagnostics plots.", images = list("plot_model1.png", "plot_model2.png"), detail = "high" ) # --- Mix of pre-built parts --- library(ggplot2) p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() msg <- create_multimodal_message( text = "Describe the scatter pattern.", images = list(image_from_plot(p, dpi = 180)) ) ## End(Not run)## Not run: library(openaiRtools) client <- OpenAI$new(api_key = "sk-xxxxxx") # --- URL image --- msg <- create_multimodal_message( text = "What is shown in this chart?", images = list("https://example.com/gdp_chart.png") ) response <- client$chat$completions$create(messages = list(msg), model = "gpt-4o") # --- Local file --- msg <- create_multimodal_message( text = "Identify any statistical issues in this residual plot.", images = list("output/resid_plot.png"), detail = "high" ) # --- Multiple images (compare two charts) --- msg <- create_multimodal_message( text = "Compare these two regression diagnostics plots.", images = list("plot_model1.png", "plot_model2.png"), detail = "high" ) # --- Mix of pre-built parts --- library(ggplot2) p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() msg <- create_multimodal_message( text = "Describe the scatter pattern.", images = list(image_from_plot(p, dpi = 180)) ) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$responses$create().
create_response(model, input, ...)create_response(model, input, ...)
model |
Character. Required. Model ID (e.g. |
input |
Required. A text string or list of message objects as the prompt. |
... |
Additional parameters passed to ResponsesClient |
The Responses API is OpenAI's newer, simpler alternative to Chat
Completions. It natively supports multi-turn conversations using
previous_response_id (no need to resend message history), and
includes built-in web search, file search, and other tools.
A response object. Access the text via
$output[[1]]$content[[1]]$text.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Simple text response resp <- create_response( model = "gpt-4o", input = "What is the difference between OLS and IV?" ) cat(resp$output[[1]]$content[[1]]$text) # Multi-turn: continue conversation using previous response ID resp1 <- create_response("gpt-4o", "What is GMM?") resp2 <- create_response( model = "gpt-4o", input = "Give me an R code example.", previous_response_id = resp1$id ) cat(resp2$output[[1]]$content[[1]]$text) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Simple text response resp <- create_response( model = "gpt-4o", input = "What is the difference between OLS and IV?" ) cat(resp$output[[1]]$content[[1]]$text) # Multi-turn: continue conversation using previous response ID resp1 <- create_response("gpt-4o", "What is GMM?") resp2 <- create_response( model = "gpt-4o", input = "Give me an R code example.", previous_response_id = resp1$id ) cat(resp2$output[[1]]$content[[1]]$text) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and creates a run on a thread.
Poll the run with retrieve_run() until status is "completed".
create_run(thread_id, assistant_id, ...)create_run(thread_id, assistant_id, ...)
thread_id |
Character. Required. The thread ID. |
assistant_id |
Character. Required. The assistant ID to run. |
... |
Additional parameters passed to RunsClient |
A run object with $id and $status.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") run <- create_run( thread_id = "thread_abc123", assistant_id = "asst_abc123" ) cat("Run ID:", run$id, "Status:", run$status) # Poll until done repeat { run <- retrieve_run("thread_abc123", run$id) if (run$status %in% c("completed", "failed", "cancelled")) break Sys.sleep(2) } ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") run <- create_run( thread_id = "thread_abc123", assistant_id = "asst_abc123" ) cat("Run ID:", run$id, "Status:", run$status) # Poll until done repeat { run <- retrieve_run("thread_abc123", run$id) if (run$status %in% c("completed", "failed", "cancelled")) break Sys.sleep(2) } ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$audio$speech$create().
Returns raw binary audio data that should be saved with writeBin().
create_speech(input, model = "tts-1", voice = "alloy", ...)create_speech(input, model = "tts-1", voice = "alloy", ...)
input |
Character. Required. The text to synthesize (max 4096 chars). |
model |
Character. TTS model: |
voice |
Character. Voice style. One of: |
... |
Additional parameters passed to SpeechClient |
A raw vector of binary audio data. Save using writeBin().
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Generate and save to MP3 audio <- create_speech( input = "The quick brown fox jumps over the lazy dog.", model = "tts-1", voice = "nova" ) writeBin(audio, "output.mp3") # High-quality WAV with slower speed audio <- create_speech( input = "Welcome to the lecture on macroeconomics.", model = "tts-1-hd", voice = "onyx", response_format = "wav", speed = 0.9 ) writeBin(audio, "lecture_intro.wav") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Generate and save to MP3 audio <- create_speech( input = "The quick brown fox jumps over the lazy dog.", model = "tts-1", voice = "nova" ) writeBin(audio, "output.mp3") # High-quality WAV with slower speed audio <- create_speech( input = "Welcome to the lecture on macroeconomics.", model = "tts-1-hd", voice = "onyx", response_format = "wav", speed = 0.9 ) writeBin(audio, "lecture_intro.wav") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and creates a new thread.
create_thread(...)create_thread(...)
... |
Parameters passed to ThreadsClient |
A thread object with $id (save this for subsequent calls).
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") thread <- create_thread() cat("Thread ID:", thread$id) # With an initial message thread <- create_thread( messages = list(list(role = "user", content = "Hello!")) ) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") thread <- create_thread() cat("Thread ID:", thread$id) # With an initial message thread <- create_thread( messages = list(list(role = "user", content = "Hello!")) ) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$audio$transcriptions$create().
create_transcription(file, model = "whisper-1", ...)create_transcription(file, model = "whisper-1", ...)
file |
Character. Required. Path to the local audio file. Supported: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm (max 25 MB). |
model |
Character. Whisper model. Default: |
... |
Additional parameters passed to
AudioTranscriptionsClient |
A list with $text containing the transcribed text (for default
JSON format), or a character string for response_format = "text".
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Basic transcription result <- create_transcription("meeting.mp3") cat(result$text) # With language hint and plain text output text <- create_transcription( file = "lecture.m4a", model = "whisper-1", language = "en", response_format = "text" ) cat(text) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Basic transcription result <- create_transcription("meeting.mp3") cat(result$text) # With language hint and plain text output text <- create_transcription( file = "lecture.m4a", model = "whisper-1", language = "en", response_format = "text" ) cat(text) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$audio$translations$create().
Always produces English output regardless of source language.
create_translation(file, model = "whisper-1", ...)create_translation(file, model = "whisper-1", ...)
file |
Character. Required. Path to the local audio file. Supported: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, webm (max 25 MB). |
model |
Character. Whisper model. Default: |
... |
Additional parameters passed to
AudioTranslationsClient |
A list with $text containing the English translation (for default
JSON format), or a character string for response_format = "text".
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Translate a Chinese audio file to English result <- create_translation("chinese_speech.mp3") cat(result$text) # Output is always in English ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Translate a Chinese audio file to English result <- create_translation("chinese_speech.mp3") cat(result$text) # Output is always in English ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and initializes a multipart upload session.
Use this when your file exceeds the 512 MB single-upload limit.
create_upload(purpose, filename, bytes, ...)create_upload(purpose, filename, bytes, ...)
purpose |
Character. Required. The intended use:
|
filename |
Character. Required. The original name of the file. |
bytes |
Integer. Required. Total file size in bytes
( |
... |
Additional parameters passed to UploadsClient |
An upload object with $id (use in add_upload_part() and
complete_upload()).
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") file_size <- file.info("huge_training.jsonl")$size upload <- create_upload( purpose = "fine-tune", filename = "huge_training.jsonl", bytes = file_size, mime_type = "application/json" ) cat("Upload ID:", upload$id) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") file_size <- file.info("huge_training.jsonl")$size upload <- create_upload( purpose = "fine-tune", filename = "huge_training.jsonl", bytes = file_size, mime_type = "application/json" ) cat("Upload ID:", upload$id) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and creates a new vector store.
create_vector_store(...)create_vector_store(...)
... |
Parameters passed to VectorStoresClient |
A vector store object with $id (save this), $name,
$status, and $file_counts.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") vs <- create_vector_store( name = "Economics Literature", file_ids = list("file-abc123", "file-def456") ) cat("Vector Store ID:", vs$id) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") vs <- create_vector_store( name = "Economics Literature", file_ids = list("file-abc123", "file-def456") ) cat("Vector Store ID:", vs$id) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and permanently deletes an assistant.
delete_assistant(assistant_id)delete_assistant(assistant_id)
assistant_id |
Character. Required. The ID of the assistant to delete. |
A list with $deleted (TRUE if successful) and $id.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- delete_assistant("asst_abc123") if (result$deleted) cat("Assistant deleted.") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- delete_assistant("asst_abc123") if (result$deleted) cat("Assistant deleted.") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and deletes a file.
delete_file(file_id)delete_file(file_id)
file_id |
Character. Required. The file ID to delete. |
A list with $deleted (TRUE if successful) and $id.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- delete_file("file-abc123") if (result$deleted) cat("File deleted successfully.") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- delete_file("file-abc123") if (result$deleted) cat("File deleted successfully.") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and deletes a fine-tuned model you own.
Only models you created via fine-tuning can be deleted.
delete_model(model)delete_model(model)
model |
Character. Required. The fine-tuned model ID to delete.
Fine-tuned model IDs have the format |
A list with $id (the deleted model ID) and
$deleted (TRUE if successful).
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- delete_model("ft:gpt-3.5-turbo:myorg:experiment:abc123") if (result$deleted) cat("Model deleted successfully.\n") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- delete_model("ft:gpt-3.5-turbo:myorg:experiment:abc123") if (result$deleted) cat("Model deleted successfully.\n") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and deletes a stored response.
delete_response(response_id)delete_response(response_id)
response_id |
Character. Required. The response ID to delete. |
A list with $deleted (TRUE if successful).
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- delete_response("resp_abc123") if (result$deleted) cat("Response deleted.") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- delete_response("resp_abc123") if (result$deleted) cat("Response deleted.") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and permanently deletes a thread.
delete_thread(thread_id)delete_thread(thread_id)
thread_id |
Character. Required. The thread ID to delete. |
A list with $deleted (TRUE) and $id.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- delete_thread("thread_abc123") if (result$deleted) cat("Thread deleted.") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- delete_thread("thread_abc123") if (result$deleted) cat("Thread deleted.") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and deletes a vector store.
This removes the search index but does NOT delete the underlying files.
delete_vector_store(vector_store_id)delete_vector_store(vector_store_id)
vector_store_id |
Character. Required. The vector store ID. |
A list with $deleted (TRUE) and $id.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- delete_vector_store("vs_abc123") if (result$deleted) cat("Vector store deleted.") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") result <- delete_vector_store("vs_abc123") if (result$deleted) cat("Vector store deleted.") ## End(Not run)
Provides text embedding (vectorization) via the OpenAI Embeddings API.
Access via client$embeddings.
Embeddings are numerical vector representations of text that capture semantic meaning. Similar texts produce similar vectors. Common uses include semantic search, clustering, classification, and recommendation systems.
new()
EmbeddingsClient$new(parent)
create()
EmbeddingsClient$create( input, model = "text-embedding-ada-002", encoding_format = NULL, dimensions = NULL, user = NULL )
clone()
The objects of this class are cloneable with this method.
EmbeddingsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Client for the OpenAI Files API. Upload, list, retrieve, and delete files
that can be used with fine-tuning, assistants, batch processing, and more.
Access via client$files.
$create(file, purpose)Upload a file
$list(...)List uploaded files, optionally filter by purpose
$retrieve(file_id)Get metadata for a specific file
$delete(file_id)Delete a file
$content(file_id)Download the raw content of a file
$wait_for_processing(file_id, ...)Poll until a file is processed
new()
FilesClient$new(parent)
create()
FilesClient$create(file, purpose)
list()
FilesClient$list(purpose = NULL, limit = NULL, after = NULL, order = NULL)
retrieve()
FilesClient$retrieve(file_id)
delete()
FilesClient$delete(file_id)
content()
FilesClient$content(file_id)
wait_for_processing()
FilesClient$wait_for_processing(file_id, timeout = 300, poll_interval = 5)
clone()
The objects of this class are cloneable with this method.
FilesClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Retrieves intermediate model checkpoints created during fine-tuning.
A checkpoint is saved after each training epoch. Access via
client$fine_tuning$jobs$checkpoints.
new()
FineTuningCheckpointsClient$new(parent)
list()
FineTuningCheckpointsClient$list( fine_tuning_job_id, after = NULL, limit = NULL )
clone()
The objects of this class are cloneable with this method.
FineTuningCheckpointsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Top-level client for the OpenAI Fine-tuning API. Fine-tuning lets you
train a custom version of a GPT model on your own examples.
Access via client$fine_tuning.
$jobsFineTuningJobsClient — Create and manage fine-tuning jobs
Upload training data (JSONL file) via client$files$create(purpose = "fine-tune")
Create a fine-tuning job with client$fine_tuning$jobs$create()
Monitor progress with client$fine_tuning$jobs$retrieve() or $list_events()
Use the resulting model ID in chat completions once status is "succeeded"
new()
FineTuningClient$new(parent)
clone()
The objects of this class are cloneable with this method.
FineTuningClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Manage fine-tuning jobs — create, list, retrieve, cancel, and monitor events.
Access via client$fine_tuning$jobs.
new()
FineTuningJobsClient$new(parent)
create()
FineTuningJobsClient$create( training_file, model = "gpt-3.5-turbo", hyperparameters = NULL, suffix = NULL, validation_file = NULL, integrations = NULL, seed = NULL, method = NULL )
list()
FineTuningJobsClient$list(after = NULL, limit = NULL)
retrieve()
FineTuningJobsClient$retrieve(fine_tuning_job_id)
cancel()
FineTuningJobsClient$cancel(fine_tuning_job_id)
list_events()
FineTuningJobsClient$list_events( fine_tuning_job_id, after = NULL, limit = NULL )
clone()
The objects of this class are cloneable with this method.
FineTuningJobsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Reads a local image file, encodes it as Base64, and wraps it in a data URI so it can be sent directly to the model without hosting the file anywhere. This is the recommended approach for local figures, screenshots, or any image not accessible via a public URL.
image_from_file(file_path, mime_type = NULL, detail = "auto")image_from_file(file_path, mime_type = NULL, detail = "auto")
file_path |
Character. Absolute or relative path to a local image
file. Supported formats: |
mime_type |
Character or
Override only if the extension is missing or wrong. |
detail |
Character. Image detail level: |
A named list (content part) ready to include in a message's
content list.
image_from_url, image_from_plot,
create_multimodal_message
## Not run: library(openaiRtools) client <- OpenAI$new(api_key = "sk-xxxxxx") # Send a local chart image img <- image_from_file("results/regression_plot.png", detail = "high") messages <- list( list( role = "user", content = list( list( type = "text", text = "This is a residuals-vs-fitted plot. Does it show heteroskedasticity?" ), img ) ) ) response <- client$chat$completions$create( messages = messages, model = "gpt-4o" ) cat(response$choices[[1]]$message$content) ## End(Not run)## Not run: library(openaiRtools) client <- OpenAI$new(api_key = "sk-xxxxxx") # Send a local chart image img <- image_from_file("results/regression_plot.png", detail = "high") messages <- list( list( role = "user", content = list( list( type = "text", text = "This is a residuals-vs-fitted plot. Does it show heteroskedasticity?" ), img ) ) ) response <- client$chat$completions$create( messages = messages, model = "gpt-4o" ) cat(response$choices[[1]]$message$content) ## End(Not run)
Renders a ggplot2 plot (or any R base graphics expression) to a temporary PNG file and encodes it as Base64, ready to be sent to a vision LLM. This lets you analyze charts produced in R without saving them manually.
image_from_plot(plot = NULL, width = 7, height = 5, dpi = 150, detail = "auto")image_from_plot(plot = NULL, width = 7, height = 5, dpi = 150, detail = "auto")
plot |
A |
width |
Numeric. Width of the saved PNG in inches. Default: |
height |
Numeric. Height of the saved PNG in inches. Default: |
dpi |
Integer. Resolution in dots per inch. Higher DPI gives sharper
images (important for text readability) but larger file size.
Default: |
detail |
Character. Image detail level passed to the API:
|
A named list (content part) ready to include in a message's
content list.
image_from_file, create_multimodal_message
## Not run: library(openaiRtools) library(ggplot2) client <- OpenAI$new(api_key = "sk-xxxxxx") # Build a ggplot2 chart p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + geom_smooth(method = "lm") + labs(title = "Car Weight vs Fuel Efficiency", x = "Weight", y = "MPG") # Send plot directly to GPT-4o response <- client$chat$completions$create( messages = list( list( role = "user", content = list( list( type = "text", text = "Describe the relationship shown in this scatter plot." ), image_from_plot(p, dpi = 150) ) ) ), model = "gpt-4o" ) cat(response$choices[[1]]$message$content) ## End(Not run)## Not run: library(openaiRtools) library(ggplot2) client <- OpenAI$new(api_key = "sk-xxxxxx") # Build a ggplot2 chart p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + geom_smooth(method = "lm") + labs(title = "Car Weight vs Fuel Efficiency", x = "Weight", y = "MPG") # Send plot directly to GPT-4o response <- client$chat$completions$create( messages = list( list( role = "user", content = list( list( type = "text", text = "Describe the relationship shown in this scatter plot." ), image_from_plot(p, dpi = 150) ) ) ), model = "gpt-4o" ) cat(response$choices[[1]]$message$content) ## End(Not run)
Builds a content part object that tells the model to fetch and analyze an image from a public web URL. The URL must be directly accessible (no login required).
image_from_url(url, detail = "auto")image_from_url(url, detail = "auto")
url |
Character. A publicly accessible image URL.
Supported formats: JPEG, PNG, GIF (static), WebP.
Example: |
detail |
Character. Controls how the model perceives the image, trading off between cost/speed and accuracy:
|
A named list (content part) to be placed inside a message's
content list. Use with create_multimodal_message
or construct messages manually.
image_from_file, image_from_plot,
create_multimodal_message
## Not run: library(openaiRtools) client <- OpenAI$new(api_key = "sk-xxxxxx") # Build an image part from a URL img <- image_from_url( url = "https://example.com/photo.jpg", detail = "low" ) # Assemble a message manually messages <- list( list( role = "user", content = list( list(type = "text", text = "What painting is this?"), img ) ) ) response <- client$chat$completions$create( messages = messages, model = "gpt-4o" ) cat(response$choices[[1]]$message$content) ## End(Not run)## Not run: library(openaiRtools) client <- OpenAI$new(api_key = "sk-xxxxxx") # Build an image part from a URL img <- image_from_url( url = "https://example.com/photo.jpg", detail = "low" ) # Assemble a message manually messages <- list( list( role = "user", content = list( list(type = "text", text = "What painting is this?"), img ) ) ) response <- client$chat$completions$create( messages = messages, model = "gpt-4o" ) cat(response$choices[[1]]$message$content) ## End(Not run)
Client for OpenAI Images API (DALL-E image generation and editing).
Access via client$images.
$create(prompt, ...)Generate a new image from a text description
$edit(image, prompt, ...)Edit an existing image using a mask
$create_variation(image, ...)Create variations of an existing image
new()
ImagesClient$new(parent)
create()
ImagesClient$create( prompt, model = "dall-e-3", n = NULL, quality = NULL, response_format = NULL, size = NULL, style = NULL, user = NULL )
edit()
ImagesClient$edit( image, prompt, mask = NULL, model = "dall-e-2", n = NULL, response_format = NULL, size = NULL, user = NULL )
create_variation()
ImagesClient$create_variation( image, model = "dall-e-2", n = NULL, response_format = NULL, size = NULL, user = NULL )
clone()
The objects of this class are cloneable with this method.
ImagesClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and lists all assistants.
list_assistants(...)list_assistants(...)
... |
Additional parameters passed to AssistantsClient |
A list with $data — a list of assistant objects, each with
$id, $name, $model, $instructions, and $tools.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") assistants <- list_assistants() for (a in assistants$data) { cat(a$id, "-", a$name %||% "(unnamed)", "\n") } ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") assistants <- list_assistants() for (a in assistants$data) { cat(a$id, "-", a$name %||% "(unnamed)", "\n") } ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and lists batch jobs.
list_batches(...)list_batches(...)
... |
Additional parameters passed to BatchClient |
A list with $data — a list of batch objects, each containing
$id, $status, $request_counts, and $output_file_id.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") batches <- list_batches(limit = 5) for (b in batches$data) cat(b$id, b$status, "\n") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") batches <- list_batches(limit = 5) for (b in batches$data) cat(b$id, b$status, "\n") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$files$list().
list_files(purpose = NULL, ...)list_files(purpose = NULL, ...)
purpose |
Character or NULL. Filter by purpose:
|
... |
Additional parameters passed to FilesClient |
A list with $data — a list of file objects, each containing
$id, $filename, $bytes, $purpose, $status, and $created_at.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # List all files all_files <- list_files() cat("Total files:", length(all_files$data)) # List only fine-tuning files ft_files <- list_files(purpose = "fine-tune") for (f in ft_files$data) cat(f$id, f$filename, "\n") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # List all files all_files <- list_files() cat("Total files:", length(all_files$data)) # List only fine-tuning files ft_files <- list_files(purpose = "fine-tune") for (f in ft_files$data) cat(f$id, f$filename, "\n") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and lists checkpoints for a fine-tuning job.
Checkpoints are saved after each epoch and can be used as models directly.
list_fine_tuning_checkpoints(fine_tuning_job_id, ...)list_fine_tuning_checkpoints(fine_tuning_job_id, ...)
fine_tuning_job_id |
Character. Required. The fine-tuning job ID. |
... |
Additional parameters passed to FineTuningCheckpointsClient |
A list with $data — a list of checkpoint objects, each containing
$fine_tuned_model_checkpoint (usable model ID), $step_number,
and $metrics (list with $train_loss, $valid_loss, etc.).
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") cps <- list_fine_tuning_checkpoints("ftjob-abc123") for (cp in cps$data) { cat("Step:", cp$step_number, "Loss:", cp$metrics$train_loss, "\n") } ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") cps <- list_fine_tuning_checkpoints("ftjob-abc123") for (cp in cps$data) { cat("Step:", cp$step_number, "Loss:", cp$metrics$train_loss, "\n") } ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and lists training events for a fine-tuning job.
Events include per-step training loss metrics and status messages.
list_fine_tuning_events(fine_tuning_job_id, ...)list_fine_tuning_events(fine_tuning_job_id, ...)
fine_tuning_job_id |
Character. Required. The fine-tuning job ID. |
... |
Additional parameters passed to FineTuningJobsClient |
A list with $data — a list of event objects, each containing
$message (description), $level, and $created_at (Unix timestamp).
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") events <- list_fine_tuning_events("ftjob-abc123", limit = 50) for (e in events$data) cat(e$message, "\n") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") events <- list_fine_tuning_events("ftjob-abc123", limit = 50) for (e in events$data) cat(e$message, "\n") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and lists fine-tuning jobs.
list_fine_tuning_jobs(...)list_fine_tuning_jobs(...)
... |
Additional parameters passed to FineTuningJobsClient |
A list with $data — a list of fine-tuning job objects, each
containing $id, $status, $model, $fine_tuned_model.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") jobs <- list_fine_tuning_jobs(limit = 5) for (j in jobs$data) cat(j$id, "-", j$status, "\n") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") jobs <- list_fine_tuning_jobs(limit = 5) for (j in jobs$data) cat(j$id, "-", j$status, "\n") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and lists messages in a thread.
After a run completes, the assistant's reply appears in this list.
list_messages(thread_id, ...)list_messages(thread_id, ...)
thread_id |
Character. Required. The thread ID. |
... |
Additional parameters passed to MessagesClient |
A list with $data — a list of message objects, newest first
(by default). Access reply text via:
msgs$data[[1]]$content[[1]]$text$value.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Read latest messages (newest first) msgs <- list_messages("thread_abc123") cat("Assistant reply:", msgs$data[[1]]$content[[1]]$text$value) # Print full conversation chronologically msgs <- list_messages("thread_abc123", order = "asc") for (m in msgs$data) { cat(toupper(m$role), ":", m$content[[1]]$text$value, "\n\n") } ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Read latest messages (newest first) msgs <- list_messages("thread_abc123") cat("Assistant reply:", msgs$data[[1]]$content[[1]]$text$value) # Print full conversation chronologically msgs <- list_messages("thread_abc123", order = "asc") for (m in msgs$data) { cat(toupper(m$role), ":", m$content[[1]]$text$value, "\n\n") } ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and returns all models available to your API key.
list_models()list_models()
A list with $data — a list of model objects, each containing
$id (model name string), $owned_by, and $created (Unix timestamp).
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") models <- list_models() # Extract all model IDs as a character vector model_ids <- sapply(models$data, `[[`, "id") cat(model_ids, sep = "\n") # Find all embedding models embed_models <- model_ids[grepl("embedding", model_ids)] cat(embed_models, sep = "\n") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") models <- list_models() # Extract all model IDs as a character vector model_ids <- sapply(models$data, `[[`, "id") cat(model_ids, sep = "\n") # Find all embedding models embed_models <- model_ids[grepl("embedding", model_ids)] cat(embed_models, sep = "\n") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and lists all vector stores.
list_vector_stores(...)list_vector_stores(...)
... |
Parameters passed to VectorStoresClient |
A list with $data — a list of vector store objects.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") stores <- list_vector_stores() for (s in stores$data) cat(s$id, "-", s$name, "\n") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") stores <- list_vector_stores() for (s in stores$data) cat(s$id, "-", s$name, "\n") ## End(Not run)
Manages messages within threads. Messages store the conversation history
between the user and the assistant.
Access via client$threads$messages.
new()
MessagesClient$new(parent)
create()
MessagesClient$create( thread_id, role, content, attachments = NULL, metadata = NULL )
list()
MessagesClient$list( thread_id, limit = NULL, order = NULL, after = NULL, before = NULL, run_id = NULL )
retrieve()
MessagesClient$retrieve(thread_id, message_id)
update()
MessagesClient$update(thread_id, message_id, metadata = NULL)
delete()
MessagesClient$delete(thread_id, message_id)
clone()
The objects of this class are cloneable with this method.
MessagesClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Client for the OpenAI Models API. Allows listing available models,
retrieving model details, and deleting fine-tuned models.
Access via client$models.
$list()List all available models
$retrieve(model)Get details of a specific model
$delete(model)Delete a fine-tuned model you own
new()
ModelsClient$new(parent)
list()
ModelsClient$list()
retrieve()
ModelsClient$retrieve(model)
delete()
ModelsClient$delete(model)
clone()
The objects of this class are cloneable with this method.
ModelsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Client for the OpenAI Moderations API. Classifies text (and optionally
images) for potentially harmful content according to OpenAI's usage policies.
Access via client$moderations.
The API returns a set of category flags and confidence scores. It is free to use and does not count against your token quota.
hate, hate/threatening, harassment, harassment/threatening,
self-harm, self-harm/intent, self-harm/instructions,
sexual, sexual/minors, violence, violence/graphic.
new()
ModerationsClient$new(parent)
create()
ModerationsClient$create(input, model = "omni-moderation-latest")
clone()
The objects of this class are cloneable with this method.
ModerationsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Most modern LLMs (GPT-4o, Claude 3, Gemini, Qwen-VL, etc.) support
multimodal input — you can send both text and images in the same message.
Images are embedded inside the content field of a "user" message
as a list of content parts.
There are three ways to provide an image:
Image URL — the model downloads it directly (image_from_url)
Local file — read and Base64-encoded automatically (image_from_file)
R plot — save a ggplot2 / base R figure and send it (image_from_plot)
Use create_multimodal_message to combine text + multiple images
into a single ready-to-use message object.
Functions to construct image content objects for sending images to vision-capable LLMs via the Chat Completions API.
Main client class for interacting with OpenAI API. Compatible with Python OpenAI SDK interface.
new()
OpenAI$new( api_key = NULL, base_url = NULL, organization = NULL, project = NULL, timeout = 600, max_retries = 2 )
build_headers()
OpenAI$build_headers()
request()
OpenAI$request( method, path, body = NULL, query = NULL, stream = FALSE, callback = NULL )
request_multipart()
OpenAI$request_multipart(method, path, ...)
request_raw()
OpenAI$request_raw(method, path, body = NULL)
clone()
The objects of this class are cloneable with this method.
OpenAI$clone(deep = FALSE)
deepWhether to make a deep clone.
OpenAI API Error
OpenAIAPIError(message, status_code = NULL, response = NULL, ...)OpenAIAPIError(message, status_code = NULL, response = NULL, ...)
message |
Error message |
status_code |
HTTP status code |
response |
Raw response object |
... |
Additional arguments |
OpenAI Connection Error
OpenAIConnectionError(message, ...)OpenAIConnectionError(message, ...)
message |
Error message |
... |
Additional arguments |
The Responses API is OpenAI's next-generation API that simplifies
multi-turn conversations (via previous_response_id), supports web search,
file search, and computer use as built-in tools, and provides a cleaner
interface than Chat Completions for complex agentic applications.
Client for the OpenAI Responses API — a new, unified API for generating
text responses, managing multi-turn conversations, and using built-in tools.
Access via client$responses.
new()
ResponsesClient$new(parent)
create()
ResponsesClient$create( model, input, instructions = NULL, previous_response_id = NULL, tools = NULL, tool_choice = NULL, parallel_tool_calls = NULL, max_output_tokens = NULL, max_completion_tokens = NULL, temperature = NULL, top_p = NULL, truncation = NULL, metadata = NULL, reasoning = NULL, service_tier = NULL, prompt_cache_key = NULL, prompt_cache_retention = NULL, include = NULL, store = NULL, stream = NULL, callback = NULL )
retrieve()
ResponsesClient$retrieve(response_id)
delete()
ResponsesClient$delete(response_id)
cancel()
ResponsesClient$cancel(response_id)
list_input_items()
ResponsesClient$list_input_items(response_id, after = NULL, limit = NULL)
clone()
The objects of this class are cloneable with this method.
ResponsesClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and retrieves a specific assistant.
retrieve_assistant(assistant_id)retrieve_assistant(assistant_id)
assistant_id |
Character. Required. The assistant ID
(e.g. |
An assistant object with $id, $name, $model,
$instructions, $tools, and $created_at.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") asst <- retrieve_assistant("asst_abc123") cat("Name:", asst$name) cat("Model:", asst$model) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") asst <- retrieve_assistant("asst_abc123") cat("Name:", asst$name) cat("Model:", asst$model) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and retrieves a specific batch.
Use this to poll status and get the output_file_id when the batch
is complete.
retrieve_batch(batch_id)retrieve_batch(batch_id)
batch_id |
Character. Required. The batch ID (e.g. |
A batch object with $status, $request_counts
($total, $completed, $failed), and $output_file_id (when done).
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") batch <- retrieve_batch("batch_abc123") cat("Status:", batch$status) if (batch$status == "completed") { raw <- retrieve_file_content(batch$output_file_id) cat(rawToChar(raw)) } ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") batch <- retrieve_batch("batch_abc123") cat("Status:", batch$status) if (batch$status == "completed") { raw <- retrieve_file_content(batch$output_file_id) cat(rawToChar(raw)) } ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and retrieves metadata for a specific file.
retrieve_file(file_id)retrieve_file(file_id)
file_id |
Character. Required. The file ID (e.g. |
A file object with $id, $filename, $bytes, $purpose,
$status, and $created_at.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") info <- retrieve_file("file-abc123") cat("Filename:", info$filename) cat("Status:", info$status) # "processed" ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") info <- retrieve_file("file-abc123") cat("Filename:", info$filename) cat("Status:", info$status) # "processed" ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and downloads the raw content of a file.
retrieve_file_content(file_id)retrieve_file_content(file_id)
file_id |
Character. Required. The file ID to download. |
A raw vector of binary content.
Use rawToChar() for text, or writeBin() to save to disk.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Download batch output file raw_data <- retrieve_file_content("file-abc123") text <- rawToChar(raw_data) cat(text) # Save to file writeBin(raw_data, "batch_results.jsonl") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Download batch output file raw_data <- retrieve_file_content("file-abc123") text <- rawToChar(raw_data) cat(text) # Save to file writeBin(raw_data, "batch_results.jsonl") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and retrieves a specific fine-tuning job.
retrieve_fine_tuning_job(fine_tuning_job_id)retrieve_fine_tuning_job(fine_tuning_job_id)
fine_tuning_job_id |
Character. Required. The fine-tuning job ID
(e.g. |
A fine-tuning job object with $status, $model, and
$fine_tuned_model (the resulting model ID when status is "succeeded").
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") job <- retrieve_fine_tuning_job("ftjob-abc123") cat("Status:", job$status) if (job$status == "succeeded") cat("Model:", job$fine_tuned_model) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") job <- retrieve_fine_tuning_job("ftjob-abc123") cat("Status:", job$status) if (job$status == "succeeded") cat("Model:", job$fine_tuned_model) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and retrieves details for a specific model.
retrieve_model(model)retrieve_model(model)
model |
Character. Required. The model ID to look up.
Examples: |
A named list with model metadata: $id, $object,
$created (Unix timestamp), $owned_by.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") info <- retrieve_model("gpt-4o") cat("ID:", info$id, "\n") cat("Owner:", info$owned_by, "\n") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") info <- retrieve_model("gpt-4o") cat("ID:", info$id, "\n") cat("Owner:", info$owned_by, "\n") ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and retrieves a stored response by its ID.
Only responses created with store = TRUE can be retrieved.
retrieve_response(response_id)retrieve_response(response_id)
response_id |
Character. Required. The response ID
(e.g. |
A response object with $output, $model, and $usage.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") resp <- retrieve_response("resp_abc123") cat(resp$output[[1]]$content[[1]]$text) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") resp <- retrieve_response("resp_abc123") cat(resp$output[[1]]$content[[1]]$text) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and retrieves a run's current status.
retrieve_run(thread_id, run_id)retrieve_run(thread_id, run_id)
thread_id |
Character. Required. The thread ID. |
run_id |
Character. Required. The run ID. |
A run object with $status ("queued", "in_progress",
"completed", "requires_action", "failed", etc.).
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") run <- retrieve_run("thread_abc123", "run_abc123") cat("Status:", run$status) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") run <- retrieve_run("thread_abc123", "run_abc123") cat("Status:", run$status) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and retrieves a thread.
retrieve_thread(thread_id)retrieve_thread(thread_id)
thread_id |
Character. Required. The thread ID to retrieve. |
A thread object with $id, $created_at, and $metadata.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") thread <- retrieve_thread("thread_abc123") cat("Created at:", thread$created_at) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") thread <- retrieve_thread("thread_abc123") cat("Created at:", thread$created_at) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and retrieves a vector store by its ID.
retrieve_vector_store(vector_store_id)retrieve_vector_store(vector_store_id)
vector_store_id |
Character. Required. The vector store ID
(e.g. |
A vector store object with $id, $name, $status,
and $file_counts.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") vs <- retrieve_vector_store("vs_abc123") cat("Name:", vs$name) cat("Files:", vs$file_counts$completed, "ready") ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") vs <- retrieve_vector_store("vs_abc123") cat("Name:", vs$name) cat("Files:", vs$file_counts$completed, "ready") ## End(Not run)
Manages runs on threads. A run executes an assistant's logic against
a thread's messages and produces a response.
Access via client$threads$runs.
"queued" → "in_progress" → "completed" (success)
or → "requires_action" (tool call needed) → "in_progress" (after submitting outputs)
or → "failed" / "cancelled" / "expired"
new()
RunsClient$new(parent)
create()
RunsClient$create( thread_id, assistant_id, model = NULL, instructions = NULL, additional_instructions = NULL, additional_messages = NULL, tools = NULL, metadata = NULL, temperature = NULL, top_p = NULL, max_prompt_tokens = NULL, max_completion_tokens = NULL, truncation_strategy = NULL, tool_choice = NULL, parallel_tool_calls = NULL, response_format = NULL, stream = NULL, callback = NULL )
list()
RunsClient$list( thread_id, limit = NULL, order = NULL, after = NULL, before = NULL )
retrieve()
RunsClient$retrieve(thread_id, run_id)
update()
RunsClient$update(thread_id, run_id, metadata = NULL)
cancel()
RunsClient$cancel(thread_id, run_id)
submit_tool_outputs()
RunsClient$submit_tool_outputs( thread_id, run_id, tool_outputs, stream = NULL, callback = NULL )
clone()
The objects of this class are cloneable with this method.
RunsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Lists and retrieves the individual steps taken during a run.
Each run may consist of multiple steps (e.g. thinking, tool calls,
message creation). Access via client$threads$runs$steps.
new()
RunStepsClient$new(parent)
list()
RunStepsClient$list( thread_id, run_id, limit = NULL, order = NULL, after = NULL, before = NULL )
retrieve()
RunStepsClient$retrieve(thread_id, run_id, step_id)
clone()
The objects of this class are cloneable with this method.
RunStepsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Converts text to spoken audio using OpenAI's TTS models.
Access via client$audio$speech.
new()
SpeechClient$new(parent)
create()
SpeechClient$create( input, model = "tts-1", voice = "alloy", response_format = NULL, speed = NULL )
clone()
The objects of this class are cloneable with this method.
SpeechClient$clone(deep = FALSE)
deepWhether to make a deep clone.
R6 class for iterating over streaming response chunks.
new()
StreamIterator$new(chunks)
next_chunk()
StreamIterator$next_chunk()
has_more()
StreamIterator$has_more()
reset()
StreamIterator$reset()
as_list()
StreamIterator$as_list()
get_full_text()
StreamIterator$get_full_text()
clone()
The objects of this class are cloneable with this method.
StreamIterator$clone(deep = FALSE)
deepWhether to make a deep clone.
Wraps a plain text string into the content-part format required by the
multimodal Chat Completions API. Useful when building message content
lists manually alongside image parts.
text_content(text)text_content(text)
text |
Character. The text string to include in the message content. |
A named list: list(type = "text", text = <text>).
image_from_url, create_multimodal_message
## Not run: part <- text_content("What do you see in this image?") # Result: list(type = "text", text = "What do you see in this image?") ## End(Not run)## Not run: part <- text_content("What do you see in this image?") # Result: list(type = "text", text = "What do you see in this image?") ## End(Not run)
A Thread stores the message history of a conversation with an Assistant. Threads are persistent: they accumulate messages over multiple runs and can be retrieved at any time.
Client for the OpenAI Threads API v2 (Beta).
Threads are persistent conversation containers for Assistants.
Access via client$threads.
$runsRunsClient — Create and manage runs on threads
$messagesMessagesClient — Add and read thread messages
Create a thread: client$threads$create()
Add user message: client$threads$messages$create(thread_id, "user", "...")
Create a run: client$threads$runs$create(thread_id, assistant_id)
Poll run until $status == "completed"
Read response: client$threads$messages$list(thread_id)
new()
ThreadsClient$new(parent)
create()
ThreadsClient$create(messages = NULL, tool_resources = NULL, metadata = NULL)
retrieve()
ThreadsClient$retrieve(thread_id)
update()
ThreadsClient$update(thread_id, ...)
delete()
ThreadsClient$delete(thread_id)
create_and_run()
ThreadsClient$create_and_run( assistant_id, thread = NULL, model = NULL, instructions = NULL, tools = NULL, tool_resources = NULL, metadata = NULL, stream = NULL, callback = NULL )
clone()
The objects of this class are cloneable with this method.
ThreadsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and updates an existing assistant.
update_assistant(assistant_id, ...)update_assistant(assistant_id, ...)
assistant_id |
Character. Required. The ID of the assistant to update. |
... |
Named fields to update. Supported: |
The updated assistant object.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") updated <- update_assistant( "asst_abc123", instructions = "You are now an expert in time series analysis.", model = "gpt-4o" ) cat("Updated model:", updated$model) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") updated <- update_assistant( "asst_abc123", instructions = "You are now an expert in time series analysis.", model = "gpt-4o" ) cat("Updated model:", updated$model) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and updates a thread's metadata.
update_thread(thread_id, ...)update_thread(thread_id, ...)
thread_id |
Character. Required. The thread ID. |
... |
Named fields to update, e.g. |
The updated thread object.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") update_thread("thread_abc123", metadata = list(topic = "GMM lecture")) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") update_thread("thread_abc123", metadata = list(topic = "GMM lecture")) ## End(Not run)
Shortcut that creates an OpenAI client from the OPENAI_API_KEY
environment variable and calls client$files$create().
upload_file(file, purpose)upload_file(file, purpose)
file |
Character or raw. Required. Local file path or raw bytes. |
purpose |
Character. Required. Intended use of the file:
|
A file object with $id (the file ID), $status, $filename,
$bytes, and other metadata.
## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Upload training data for fine-tuning file_obj <- upload_file("my_training_data.jsonl", purpose = "fine-tune") cat("Uploaded file ID:", file_obj$id) # Upload a document for an Assistant file_obj <- upload_file("research_paper.pdf", purpose = "assistants") cat("File ID:", file_obj$id) ## End(Not run)## Not run: Sys.setenv(OPENAI_API_KEY = "sk-xxxxxx") # Upload training data for fine-tuning file_obj <- upload_file("my_training_data.jsonl", purpose = "fine-tune") cat("Uploaded file ID:", file_obj$id) # Upload a document for an Assistant file_obj <- upload_file("research_paper.pdf", purpose = "assistants") cat("File ID:", file_obj$id) ## End(Not run)
The Uploads API is designed for files larger than what the Files API can handle in a single request. You split the file into parts, upload each part, then finalize the upload to get a standard file object.
Client for the OpenAI Uploads API. Upload large files in multiple parts
(multipart upload) when the file exceeds the 512 MB Files API limit.
Access via client$uploads.
$create() — Initialize the upload session, get an upload_id
$add_part() — Upload each chunk of the file (called multiple times)
$complete() — Finalize and assemble the file; returns a File object
(Optional) $cancel() — Abort if needed
new()
UploadsClient$new(parent)
create()
UploadsClient$create(purpose, filename, bytes, mime_type = NULL)
add_part()
UploadsClient$add_part(upload_id, data)
complete()
UploadsClient$complete(upload_id, part_ids, md5 = NULL)
cancel()
UploadsClient$cancel(upload_id)
clone()
The objects of this class are cloneable with this method.
UploadsClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Add multiple files to a vector store in a single batch operation.
More efficient than adding files one-by-one when loading many files.
Access via client$vector_stores$file_batches.
new()
VectorStoreFileBatchesClient$new(parent)
create()
VectorStoreFileBatchesClient$create( vector_store_id, file_ids, chunking_strategy = NULL )
retrieve()
VectorStoreFileBatchesClient$retrieve(vector_store_id, batch_id)
cancel()
VectorStoreFileBatchesClient$cancel(vector_store_id, batch_id)
list_files()
VectorStoreFileBatchesClient$list_files( vector_store_id, batch_id, limit = NULL, order = NULL, after = NULL, before = NULL )
clone()
The objects of this class are cloneable with this method.
VectorStoreFileBatchesClient$clone(deep = FALSE)
deepWhether to make a deep clone.
Manages individual files within a vector store. Adding a file triggers
automatic chunking and embedding.
Access via client$vector_stores$files.
new()
VectorStoreFilesClient$new(parent)
create()
VectorStoreFilesClient$create( vector_store_id, file_id, chunking_strategy = NULL )
list()
VectorStoreFilesClient$list( vector_store_id, limit = NULL, order = NULL, after = NULL, before = NULL, filter = NULL )
retrieve()
VectorStoreFilesClient$retrieve(vector_store_id, file_id)
update()
VectorStoreFilesClient$update(vector_store_id, file_id, attributes = NULL)
delete()
VectorStoreFilesClient$delete(vector_store_id, file_id)
content()
VectorStoreFilesClient$content(vector_store_id, file_id)
clone()
The objects of this class are cloneable with this method.
VectorStoreFilesClient$clone(deep = FALSE)
deepWhether to make a deep clone.
A vector store automatically chunks, embeds, and indexes files so that
an Assistant with the file_search tool can search over them using
natural language queries.
Client for the OpenAI Vector Stores API v2 (Beta).
Vector stores enable semantic file search for Assistants.
Access via client$vector_stores.
$filesVectorStoreFilesClient — Add/remove files from a store
$file_batchesVectorStoreFileBatchesClient — Batch-add files
Upload files: client$files$create(file, purpose = "assistants")
Create vector store: client$vector_stores$create(name = "...")
Add files: client$vector_stores$files$create(store_id, file_id)
Attach to assistant via tool_resources in client$assistants$create()
new()
VectorStoresClient$new(parent)
create()
VectorStoresClient$create( name = NULL, file_ids = NULL, expires_after = NULL, chunking_strategy = NULL, metadata = NULL )
list()
VectorStoresClient$list( limit = NULL, order = NULL, after = NULL, before = NULL )
retrieve()
VectorStoresClient$retrieve(vector_store_id)
update()
VectorStoresClient$update(vector_store_id, ...)
delete()
VectorStoresClient$delete(vector_store_id)
search()
VectorStoresClient$search( vector_store_id, query, filter = NULL, max_num_results = NULL, ranking_options = NULL, rewrite_query = NULL )
clone()
The objects of this class are cloneable with this method.
VectorStoresClient$clone(deep = FALSE)
deepWhether to make a deep clone.