irudnyts / openai

An R package-wrapper around OpenAI API
https://irudnyts.github.io/openai/
Other
164 stars 28 forks source link

Allow for json mode #54

Open LukasWallrich opened 8 months ago

LukasWallrich commented 8 months ago

It would be great to use JSON mode, yet even with the development version, I don't see how to pass that parameter. Could that maybe be added?

https://platform.openai.com/docs/guides/text-generation/json-mode

irudnyts commented 7 months ago

@LukasWallrich, this feature was actually in the development version. But there are a couple of pitfalls that require care. Please see an example below with commented points:

remotes::install_github("irudnyts/openai", ref = "r6")
library(openai)

client <- OpenAI()
completion <- client$chat$completions$create(
    model = "gpt-3.5-turbo-1106", # ☝️ must be either "gpt-4-1106-preview" or "gpt-3.5-turbo-1106"
    messages = list(list("role" = "user", "content" = "What's up? Answer in JSON.")), # ☝️ You must include something like the answer should be in JSON
    response_format = list("type" = "json_object")
)

completion$choices[[1]]$message$content