如何用 PYTHON 創(chuàng)建 CHATGPT 克隆機(jī)器人
在本文中,我們將了解使用 ChatGPT API 和 gradio 在 Python 中構(gòu)建聊天應(yīng)用程序和應(yīng)答機(jī)器人所涉及的步驟。
使用 Python 開發(fā)聊天應(yīng)用程序可以為 ChatGPT 網(wǎng)站提供更多控制和靈活性。您可以根據(jù)需要自定義和擴(kuò)展聊天應(yīng)用程序。它還可以幫助您與現(xiàn)有系統(tǒng)和其他 API 集成。
什么是Gradio?
Gradio 是一個(gè) Python 庫,可以輕松為預(yù)測(cè)和生成模型創(chuàng)建可定制的用戶界面,使您可以快速構(gòu)建交互式應(yīng)用程序,而無需豐富的前端開發(fā)經(jīng)驗(yàn)。
請(qǐng)參閱下面使用 Gradio 的一些好處。
快速模型:通過使用 Gradio,您可以快速迭代和試驗(yàn)不同的模型配置和用戶界面,而無需編寫大量代碼。
無需前端開發(fā)技能:您無需成為前端開發(fā)專家即可使用 Gradio 創(chuàng)建交互式應(yīng)用程序。它解決了構(gòu)建用戶界面的復(fù)雜性,使您能夠?qū)W⒂谀P偷墓δ堋?/p>
多輸入和多輸出支持: Gradio 支持具有多個(gè)輸入和輸出的模型,使其能夠靈活地適應(yīng)各種人工智能應(yīng)用。
實(shí)時(shí)反饋: Gradio 提供實(shí)時(shí)反饋,使用戶可以查看結(jié)果并輕松與模型交互。
共享和部署: Gradio 使共享和部署 Web 應(yīng)用程序變得簡(jiǎn)單。
如何獲取 ChatGPT API
首先,第一步也是最重要的一步是使用此鏈接進(jìn)行注冊(cè):platform.openai.com。您可以使用現(xiàn)有的 Google 或 Microsoft 帳戶輕松注冊(cè)。注冊(cè)后,您將需要獲取秘密 API 密鑰才能使用該 API。它看起來像下面這樣。請(qǐng)務(wù)必復(fù)制您的 API 密鑰并保留以供將來參考。
sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
完成注冊(cè)過程后,您將收到 5 美元的免費(fèi)贈(zèng)款,用于測(cè)試 ChatGPT API。該補(bǔ)助金將在 3 個(gè)月后到期。贈(zèng)款用完后,每用于 GPT-3.5 的 1000 個(gè)代幣,您將需要支付 0.0015 美元。令牌本質(zhì)上被視為單詞。請(qǐng)務(wù)必對(duì)您的 API 密鑰保密,不要與他人共享,因?yàn)槟鷮⒊袚?dān)因使用它們而產(chǎn)生的任何費(fèi)用。
對(duì)于具有 8,000 個(gè)上下文長(zhǎng)度的GPT-4模型(例如 gpt-4),定價(jià)相對(duì)高于 GPT-3.5 模型。該型號(hào)的定價(jià)如下:
$0.03/1000 提示代幣
$0.06/1000 個(gè)采樣代幣
對(duì)于具有較高上下文長(zhǎng)度 32,000 的 GPT-4 模型(例如 gpt-4-32k),定價(jià)是具有 8K 上下文長(zhǎng)度的模型的兩倍。
$0.06/1000 提示代幣
$0.12/1000 個(gè)采樣代幣
演示:ChatGPT 克隆
請(qǐng)參閱下面的 GIF 圖片,其中顯示了 ChatGPT 的外觀和工作原理。
ChatGPT 的外觀和工作原理
安裝所需的包
確保安裝這 3 個(gè) python 包gradio openai kivy。kivy 包將幫助您單擊按鈕將 ChatGPT 輸出復(fù)制到剪貼板。
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 克隆的特點(diǎn)
ChatGPT 克隆的主要特點(diǎn)如下:
復(fù)制上次回復(fù):用戶可以輕松復(fù)制ChatGPT生成的上次回復(fù),方便參考或分享。
清除歷史記錄:它提供清除對(duì)話歷史記錄的選項(xiàng),使用戶能夠重新開始。
能夠停止處理正在運(yùn)行的代碼:如果在聊天中執(zhí)行代碼,ChatGPT Clone 允許用戶根據(jù)需要停止處理。當(dāng)它長(zhǎng)時(shí)間運(yùn)行并且不返回任何內(nèi)容時(shí)停止處理是很有用的。
模型類型之間輕松切換:ChatGPT Clone 允許您在 GPT-3.5 和 GPT-4 之間切換。
如何啟用ChatGPT的對(duì)話記憶
默認(rèn)情況下,ChatGPT API 不會(huì)保留之前對(duì)話的內(nèi)存。每個(gè) API 請(qǐng)求都被視為一個(gè)單獨(dú)的聊天會(huì)話,因此當(dāng) ChatGPT 響應(yīng)您當(dāng)前的查詢時(shí),它不會(huì)調(diào)用您之前問題中的任何信息。
如果您想通過提出進(jìn)一步的問題來改進(jìn) ChatGPT 的響應(yīng),這可能是一個(gè)缺點(diǎn)。它還可以幫助您設(shè)計(jì)給 ChatGPT 的提示。為了讓 ChatGPT 記住之前的對(duì)話,您需要在每次與其交互時(shí)提供上下文。
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