Skip to contents

The write_code function prompts the user to provide a plain English description of a program or function and the programming language it should be written in. The function then generates the code based on the user's input and writes it to a specified file.

Usage

write_code(filename, chatlog_id = NULL, ..., overwrite = FALSE)

Arguments

filename

A character string representing the name of the file where the generated code will be saved.

chatlog_id

An optional character string, the ID of the chatlog that keeps the conversation history. The default, NULL, uses one session per file, keyed by the file's normalized path, so edit_code() on the same file continues the conversation and other files are never sent along.

...

Additional arguments to pass to the chat_completion() function.

overwrite

Logical. If FALSE (default) and filename already exists, the function stops before doing anything else (no prompt, no API call, and the file is left untouched). If TRUE, an existing file is replaced, but only once the code has been generated.

Value

Returns the name of the file containing the generated code.

Details

write_code() is interactive: it reads the instructions from the console, and in a non-interactive session (e.g. Rscript) it stops at once with an error of class openair_not_interactive. In RStudio the file is shown in the editor; elsewhere it is only written.

The file is created (or replaced) only after the API returned code: a code block, or a reply without one that is entirely R code. If the call fails or no code is returned, nothing is written; the explanatory text around a code block is never written to the file. The instructions and the reply are stored in the session only once a complete reply has arrived.

Author

Ulrich Matter

Examples

if (FALSE) { # \dontrun{
# Generate code based on user input and save it to a file
generated_code_file <- write_code(tempfile(fileext = ".R"))

# Check the content of the generated code file
cat(readLines(generated_code_file), sep = "\n")

# Clean up
unlink(generated_code_file)
} # }