当前位置:首页|资讯|ChatGPT

如何用 PYTHON 创建 CHATGPT 克隆机器人

作者:科技前沿AI发布时间:2023-06-27

在本文中,我们将了解使用 ChatGPT API 和 gradio 在 Python 中构建聊天应用程序和应答机器人所涉及的步骤。

使用 Python 开发聊天应用程序可以为 ChatGPT 网站提供更多控制和灵活性。您可以根据需要自定义和扩展聊天应用程序。它还可以帮助您与现有系统和其他 API 集成。

什么是Gradio?

Gradio 是一个 Python 库,可以轻松为预测和生成模型创建可定制的用户界面,使您可以快速构建交互式应用程序,而无需丰富的前端开发经验。

请参阅下面使用 Gradio 的一些好处。

  1. 快速模型:通过使用 Gradio,您可以快速迭代和试验不同的模型配置和用户界面,而无需编写大量代码。

  2. 无需前端开发技能:您无需成为前端开发专家即可使用 Gradio 创建交互式应用程序。它解决了构建用户界面的复杂性,使您能够专注于模型的功能。

  3. 多输入和多输出支持: Gradio 支持具有多个输入和输出的模型,使其能够灵活地适应各种人工智能应用。

  4. 实时反馈: Gradio 提供实时反馈,使用户可以查看结果并轻松与模型交互。

  5. 共享和部署: Gradio 使共享和部署 Web 应用程序变得简单。

如何获取 ChatGPT API

首先,第一步也是最重要的一步是使用此链接进行注册:platform.openai.com。您可以使用现有的 Google 或 Microsoft 帐户轻松注册。注册后,您将需要获取秘密 API 密钥才能使用该 API。它看起来像下面这样。请务必复制您的 API 密钥并保留以供将来参考。

sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

完成注册过程后,您将收到 5 美元的免费赠款,用于测试 ChatGPT API。该补助金将在 3 个月后到期。赠款用完后,每用于 GPT-3.5 的 1000 个代币,您将需要支付 0.0015 美元。令牌本质上被视为单词。请务必对您的 API 密钥保密,不要与他人共享,因为您将承担因使用它们而产生的任何费用。

对于具有 8,000 个上下文长度的GPT-4模型(例如 gpt-4),定价相对高于 GPT-3.5 模型。该型号的定价如下:

  • $0.03/1000 提示代币

  • $0.06/1000 个采样代币

对于具有较高上下文长度 32,000 的 GPT-4 模型(例如 gpt-4-32k),定价是具有 8K 上下文长度的模型的两倍。

  • $0.06/1000 提示代币

  • $0.12/1000 个采样代币

演示:ChatGPT 克隆

请参阅下面的 GIF 图片,其中显示了 ChatGPT 的外观和工作原理。

ChatGPT 的外观和工作原理

安装所需的包

确保安装这 3 个 python 包gradio openai kivy。kivy 包将帮助您单击按钮将 ChatGPT 输出复制到剪贴板。

pip install gradio openai kivy

Python代码:ChatGPT克隆

import gradio as grimport openaifrom kivy.core.clipboard import Clipboard

prompt = "Send a message"
    def chat(prompt, apiKey, model):
    error_message = ""
    try:    
        response = openai.ChatCompletion.create(
          model = model,
          api_key = apiKey,
          messages = [{'role': 'user', 'content': prompt}],
          temperature = 0.7  
        )
        
    except Exception as e:
        error_message = str(e)

    if error_message:
        return "An error occurred: {}".format(error_message)
    else:
        return response['choices'][0]['message']['content']
        def chatGPT(userMsg, history, modelType, apiKey):
    history = history or []
    comb = list(sum(history, ()))
    comb.append(userMsg)
    prompt = ' '.join(comb)
    output = chat(prompt, apiKey, modelType)
    history.append((userMsg, output))
    return history, history    
def lastReply(history):
    if history is None:
        result = ""
    else:    
        result = history[-1][1]
        Clipboard.copy(result)
    return resultwith gr.Blocks(theme=gr.themes.Monochrome(), css="pre {background: #f6f6f6} #submit {background-color: #fcf5ef; color: #c88f58;} #stop, #clear, #copy {max-width: 165px;} #myrow {justify-content: center;}") as demo:
    gr.Markdown("""<center><h1>🚀 ChatGPT</h1></center>""")
    with gr.Row():
        with gr.Column(scale=0.5):
            modelType = gr.Dropdown(choices=["gpt-3.5-turbo", "gpt-4"], value="gpt-3.5-turbo", label="Model", info="Select your model type" )
        with gr.Column(scale=0.5, min_width=0):            
            apiKey = gr.Textbox(label="API Key", info="Enter API Key", lines=1, placeholder="sk-xxxxxxxxxxx")
    chatbot = gr.Chatbot().style(height=250)
    state = gr.State()
    with gr.Row():
        with gr.Column(scale=0.85):
            msg = gr.Textbox(show_label=False, placeholder=prompt).style(container=False)
        with gr.Column(scale=0.15, min_width=0):
            submit = gr.Button("Submit", elem_id="submit")
    with gr.Row(elem_id="myrow"):
        stop = gr.Button("🛑 Stop", elem_id="stop")        
        clear = gr.Button("🗑️ Clear History", elem_id="clear")
        copy = gr.Button("📋 Copy last reply", elem_id="copy")
    clear.click(lambda: (None, None, None), None, outputs=[chatbot, state, msg], queue=False)        
    submit_event = submit.click(chatGPT, inputs=[msg, state, modelType, apiKey], outputs=[chatbot, state])
    submit2_event = msg.submit(chatGPT, inputs=[msg, state, modelType, apiKey], outputs=[chatbot, state])
    stop.click(None, None, None, cancels=[submit_event, submit2_event])
    copy.click(lastReply, inputs=[state], outputs=None)demo.queue().launch(inbrowser=True, debug=True)

ChatGPT 克隆的特点

ChatGPT 克隆的主要特点如下:

  • 复制上次回复:用户可以轻松复制ChatGPT生成的上次回复,方便参考或分享。

  • 清除历史记录:它提供清除对话历史记录的选项,使用户能够重新开始。

  • 能够停止处理正在运行的代码:如果在聊天中执行代码,ChatGPT Clone 允许用户根据需要停止处理。当它长时间运行并且不返回任何内容时停止处理是很有用的。

  • 模型类型之间轻松切换:ChatGPT Clone 允许您在 GPT-3.5 和 GPT-4 之间切换。

如何启用ChatGPT的对话记忆

默认情况下,ChatGPT API 不会保留之前对话的内存。每个 API 请求都被视为一个单独的聊天会话,因此当 ChatGPT 响应您当前的查询时,它不会调用您之前问题中的任何信息。

如果您想通过提出进一步的问题来改进 ChatGPT 的响应,这可能是一个缺点。它还可以帮助您设计给 ChatGPT 的提示。为了让 ChatGPT 记住之前的对话,您需要在每次与其交互时提供上下文。

import openaiimport os os.environ['OPENAI_API_KEY'] = "sk-xxxxxxxxxxxxxxxxxxxxxxx"openai.api_key = os.getenv("OPENAI_API_KEY")chatHistory = []def chat(prompt, modelName="gpt-3.5-turbo", temperature=0.7, top_p=1):    params = {        "model": modelName,        "temperature": temperature,        "top_p": top_p    }    chatHistory.append({"role": "user", "content": prompt})    response = openai.ChatCompletion.create(        **params,        messages=chatHistory    )    answer = response["choices"][0]["message"]["content"].strip()    chatHistory.append({"role": "assistant", "content": answer})    return answer chat("2+2")4chat("square of it")16chat("add 3 to it")19




Copyright © 2024 aigcdaily.cn  北京智识时代科技有限公司  版权所有  京ICP备2023006237号-1