ChatGPT函数调用示例


如果有异常,可以通过逐条删除重试。

确认自动调用函数时,会根据需要自动通过gRPC调用我的服务器上部署的墨尔本市房价异常值查询函数
get_Melbourne_Outliers
函数调用有2个参数
1、算法:
字符串类型
cat
lgbm
xgb
gbr
rf
svm
blend
2、阈值:
>0的整数
通常20~80
即20%~80%
show with app
  • global.R
  • server.R
  • ui.R
library(reticulate)
library(stringr)

# Load OpenAI API
print(getwd())
path<- "/home/jean/scripts/OpenAIFunctionCall.py"
print(path)
#使用指定的Conda虚拟环境"openai"运行Python程序
use_condaenv(condaenv="base", conda = "/usr/lib64/anaconda3/bin/conda", required = TRUE)
source_python(path)

context<-list()
context[[1]]<-list(role="system",content="You are a helpful assistant.")
function(input, output, session) {
  # 格式化输出,插入对话者身份前缀。
  formatOutput<-function(messages){
    outStr<-""
    for(i in 2: length(messages)){
      message = messages[[i]]
      # print(message)
      if (i%%2==0){
        outStr<-paste(outStr,"User: ",message[["content"]],"\n",sep="")
      }else{
        if(is.null(message[["content"]]))
          outStr<-paste(outStr,"AI: ",message[["function_call"]],"\n\n",sep="")
        else
          outStr<-paste(outStr,"AI: ",message[["content"]],"\n\n",sep="")
      }
    }
    return (outStr)
  }
  
  ifContext<- reactive({
    input$ifContext
  })
  
  ifFunctionCall<- reactive({
    input$ifFunctionCall
  })
  
  prompt<- reactive({
    input$prompt
  })
  
  observeEvent(input$clearContext,{
    session$userData$context<- context
    updateTextAreaInput(session, "context", value = "")
  })

  observeEvent(input$clearLast,{
    context<-session$userData$context
    context<-context[1:length(context)-1]
    outStr<- formatOutput(context)
    session$userData$context<-context
    updateTextAreaInput(session, "context", value = outStr)
  })  
  
  observeEvent(input$sendout,{
    if(ifContext() && ! is.null(session$userData$context)){
      temp<-session$userData$context
    } else{
      temp<- context
    }
    
    temp[[length(temp)+1]]<-list(role="user",content=prompt())
    # Show notification while querying.
    id <- showNotification("正在询问ChatGPT...", duration = NULL, closeButton = FALSE)
    on.exit(removeNotification(id), add = TRUE)
    
    # Catch exceptions happened while calling OpenAI API
    errmessage = NULL
    tryCatch({
      temp<-conversation(temp, ifFunctionCall())
    },error = function(err) {
      # print(err)
      # Use <<- to pass error message outside
      errmessage<<-list(role="assistant",content=paste("ERROR:  ",err))
    })
    if (!is.null(errmessage))
      temp[[length(temp)+1]]<-errmessage
    
    session$userData$context<- temp
    outStr<-formatOutput(temp)
    updateTextAreaInput(session, "context", value = outStr)
    updateTextAreaInput(session, "prompt", value = "")
  })
  
}
fluidPage(
  sidebarLayout(
    # Sidebar 
    sidebarPanel(
      # Application title
      tags$h3("ChatGPT函数调用示例"),
      checkboxInput("ifContext","是否包括上下文:", value = TRUE),
      actionButton("clearContext", "清除上下文", class = "btn-cleear"),
      actionButton("clearLast", "清除最后一条", class = "btn-cleear"),
      tags$div(HTML("<br/>如果有异常,可以通过逐条删除重试。")),
      checkboxInput("ifFunctionCall","是否自动调用函数:", value = TRUE),
      tags$div(HTML(
        "<br/>
        确认自动调用函数时,会根据需要自动通过gRPC调用我的服务器上部署的墨尔本市房价异常值查询函数<br/>
        get_Melbourne_Outliers<br/>
        函数调用有2个参数<br/>
        1、算法:<br/>
        字符串类型<br/>
        cat<br/>
        lgbm<br/>
        xgb<br/>
        gbr<br/>
        rf<br/>
        svm<br/>
        blend<br/>
        2、阈值:<br/>
        >0的整数<br/>
        通常20~80<br/>
        即20%~80%<br/>
        "
      ))
      # 1/6
      # width = 2
    ),
    # Main 
    mainPanel(
      textAreaInput("context","对话记录",width="100%", rows =21, resize="vertical", value =""),  
      # 插入javascript,禁止自己修改 context textAreaInput
      tags$script(HTML("
        var context = document.getElementById('context');
        context.readOnly = true;
      ")),
      tags$h6(" "),
      textAreaInput("prompt","输入:",width="100%", rows =4, resize="vertical", value =""),  
      actionButton("sendout", "提交", class = "btn-success"),
      # 5/6
      # width = 10
    )
  )
)