-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy path04-structured.R
More file actions
31 lines (27 loc) · 881 Bytes
/
04-structured.R
File metadata and controls
31 lines (27 loc) · 881 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
library(dotenv) # Will read OPENAI_API_KEY from .env file
library(ellmer)
# Define the structured data specification using ellmer's `type_` functions
fruit_schema <- type_object(
"A list of fruits and their colors.",
fruit = type_array(
items = type_object(
name = type_string("The name of the fruit."),
color = type_string("The color of the fruit.")
)
)
)
# Create a chat object with a specific system prompt
chat <- chat_openai(
model = "gpt-4.1",
system_prompt = "You are a helpful assistant. Always respond in valid JSON format."
)
# Function to get structured response
get_structured_response <- function(prompt) {
chat$extract_data(
prompt,
type = fruit_schema
)
}
# Example usage
result <- get_structured_response("Give me a list of 3 fruits with their colors")
print(jsonlite::toJSON(result, auto_unbox = TRUE, pretty = TRUE))