自从chatgpt开放了gpt-3.5-turbo
的API后,调用API的成本大大降低,今天使用网页版chatgpt写一个调用gpt-3.5-turbo
进行聊天的shiny程序。成品shiny代码如下:
# 加载必要的包和库
library(shiny)
library(openssl)
library(openai)
library(httr)
library(jsonlite)
library(htmltools)
library(markdown)
Sys.setenv("OPENAI_API_KEY"="你自己的API")
set_config(use_proxy(url="代理服务器ip或者是开了代理服务器的本地ip", port="代理服务器提供的sock端口"))
# 使用 Shiny 库构建用户界面
ui <- fluidPage(
titlePanel("ChatGPT"),
sidebarLayout(
sidebarPanel(
div(
tags$textarea(
id = "message",
class = "form-control",
rows = 2,
maxlength = 5000,
onkeypress = "if (event.keyCode == 13) { event.preventDefault(); $('#send').click(); }",
placeholder = "Type here..."),
style = "width:100%;"
),
actionButton("send", "Send"),
actionButton("clear", "Clear")
),
mainPanel(
uiOutput("chat_history")
)
)
)
# 定义服务器逻辑
server <- function(input, output) {
response_finally <- reactiveValues(chat_history = data.frame(
timestamp = character(),
role = character(),
content = character()
))
send_message <- function() {
new_message <- list(
list(
"role" = "user",
"content" = input$message
)
)
# 加入缓冲提示
showNotification(id = "wait","正在等待API响应...", type = "error", duration = NULL)
response <- create_chat_completion(messages = new_message,model = "gpt-3.5-turbo")$choices$message.content
# 移除缓冲提示
removeNotification(id = "wait")
timestamp <- format(Sys.time(), "%Y-%m-%d %H:%M:%S")
role <- "ChatGPT"
content <- response
new_row <- data.frame(timestamp, role, content, stringsAsFactors = FALSE)
response_finally$chat_history <- rbind(response_finally$chat_history, new_row)
}
observeEvent(input$send, {
send_message()
})
observeEvent(input$message, {
if (nchar(input$message) >= 50) {
send_message()
updateTextInput(session, "message", "")
}
})
observeEvent(input$clear, {
response_finally$chat_history <- data.frame(
timestamp = character(),
role = character(),
content = character(),
stringsAsFactors = FALSE
)
})
output$chat_history <- renderUI({
chat_md <- apply(response_finally$chat_history, 1, function(row) {
content <- row["content"]
# 生成Markdown输出
paste0("**[", row["timestamp"], "] ", row["role"], ":** ", content, "\n\n")
})
chat_html <- markdownToHTML(paste(chat_md, collapse = ""))
HTML(chat_html)
})
}
# 运行 Shiny 应用
shinyApp(ui = ui, server = server)
image.png
网友评论