Last active
October 21, 2024 22:34
-
-
Save jimbrig/8eb08f9c5862d52243bc4c0042a5cac1 to your computer and use it in GitHub Desktop.
openrouter.R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(httr2) | |
call_openrouter <- function(prompt, model = "openai/gpt-3.5-turbo") { | |
req <- request("https://openrouter.ai/api/v1/chat/completions") %>% | |
req_headers( | |
"Content-Type" = "application/json", | |
"Authorization" = paste("Bearer", Sys.getenv("OPENROUTER_API_KEY")), | |
"HTTP-Referer" = "https://your-site-url.com", # Optional | |
"X-Title" = "Your Site Name" # Optional | |
) %>% | |
req_body_json(list( | |
model = model, | |
messages = list(list(role = "user", content = prompt)) | |
)) %>% | |
req_perform() | |
resp <- resp_body_json(req) | |
return(resp$choices[[1]]$message$content) | |
} | |
result <- call_openrouter("What is the capital of France?") | |
print(result) | |
# curl converter | |
request("https://openrouter.ai/api/v1/chat/completions") |> | |
req_method("POST") |> | |
req_headers(Authorization = paste0("Bearer ", Sys.getenv("OPENROUTER_API_KEY"))) |> | |
req_body_raw( | |
'{\n "model": "openai/gpt-3.5-turbo",\n "messages": [\n {\n "role": "user",\n "content": "What is the meaning of life?"\n }\n ]\n \n}', | |
type = "application/json" | |
) |> | |
req_perform() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment