亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

首頁 后端開發(fā) Python教程 教程:創(chuàng)建您自己的 AI 學(xué)習(xí)伙伴

教程:創(chuàng)建您自己的 AI 學(xué)習(xí)伙伴

Dec 03, 2024 pm 07:36 PM

Tutorial: Create Your Own AI Study Buddy

在學(xué)習(xí)新東西時是否感到不知所措?就像你淹沒在信息中但實際上沒有吸收任何東西?我們都去過那里。擁有一個了解您的水平并以簡單易懂的方式解釋事物的個性化學(xué)習(xí)伙伴不是很棒嗎?這正是我們要共同構(gòu)建的。

本教程將向您展示如何將 BotHub API 與 PyQt5 結(jié)合起來創(chuàng)建一個交互式且適應(yīng)性強的學(xué)習(xí)工具。它不僅僅是另一個聊天機器人;它是一個聊天機器人。它更像是私人導(dǎo)師,24/7 全天候提供服務(wù)。

準備您的工作空間

在開始構(gòu)建之前,讓我們先收集工具。我們需要一些關(guān)鍵的 Python 庫:

import os
import datetime
import json
from dataclasses import dataclass
from typing import List, Dict
from openai import OpenAI
from dotenv import load_dotenv
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtGui import QMovie
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QTextEdit, QRadioButton, QButtonGroup, QPushButton, QGroupBox, QListWidget, QListWidgetItem, QTabWidget, QFileDialog, QComboBox, QCheckBox, QMessageBox, QDialogButtonBox, QSpinBox, QFormLayout, QDialog, QDateEdit)

將這些庫視為工具包的不同部分。有些處理基礎(chǔ)知識,例如文件管理 (os)、計時 (datetime) 和數(shù)據(jù)處理 (json)。其他的,比如數(shù)據(jù)類和類型,可以幫助我們編寫干凈、有組織的代碼。真正的魔力發(fā)生在 openai 上,它讓我們能夠利用人工智能的力量。 dotenv 保證我們敏感信息(如 API 密鑰)的安全。最后,PyQt5 幫助我們創(chuàng)建了一個漂亮且直觀的用戶界面。

制定用戶請求

為了與我們的 AI 進行通信,我們將創(chuàng)建一個 UserRequest 類。這有助于組織用戶提供的信息:

@dataclass
class UserRequest:
   query: str
   user_level: str
   preferences: Dict

使用方便的 @dataclass 裝飾器,我們定義了三個關(guān)鍵信息:用戶的查詢(他們要問什么)、他們的用戶級別(初級、中級或高級)以及他們的偏好(比如他們想要查詢多長時間)回應(yīng)是)。這將所有內(nèi)容整齊地打包到一個對象中。

記住用戶會話

為了使學(xué)習(xí)體驗真正個性化,我們需要記住用戶做了什么以及他們喜歡如何學(xué)習(xí)。這就是 UserSession 類的用武之地:

class UserSession:
   def __init__(self):
       self.history: List[Dict] = []
       self.preferences: Dict = {}
       self.level: str = "beginner"


   def add_to_history(self, query, response):
       self.history.append({"query": query, "response": response, "timestamp": datetime.datetime.now().isoformat()})


   def update_preferences(self, new_preferences):
       self.preferences.update(new_preferences)

UserSession 跟蹤對話歷史記錄、用戶的首選項及其當(dāng)前級別。這就像有一個專門的助手,可以記住一切并適應(yīng)用戶的需求。

行動的大腦:教育助理

EducationalAssistant 類是我們應(yīng)用程序的核心。它負責(zé)與 BotHub API 交互:

class EducationalAssistant:
   def __init__(self):
       load_dotenv()
       self.client = OpenAI(api_key=os.getenv('BOTHUB_API_KEY'), base_url='https://bothub.chat/api/v2/openai/v1')
       self.session = UserSession()


   def generate_prompt(self, request):
       prompt = f"""As an educational assistant, provide a response for a {request.user_level} level student.
       Query: {request.query}\n"""


       if request.preferences:
           prompt += "Consider these preferences:\n"
           for key, value in request.preferences.items():
               if key == "response_length":
                   prompt += f"Desired Length: Approximately {value} words\n"
               elif key == "include_examples" and value:
                   prompt += "Include Examples: Yes\n"
               else:
                   prompt += f"{key.capitalize()}: {value}\n"


       prompt += "Please provide a detailed explanation."
       return prompt
   def generate_text_response(self, request):
       try:
           response = self.client.chat.completions.create(
               model="claude-3.5-sonnet", // u can use any model in "Models available" on BotHub
               messages=[
                   {"role": "system", "content": "You are an educational assistant."},
                   {"role": "user", "content": self.generate_prompt(request)}
               ]
           )
           return response.choices[0].message.content
       except Exception as e:
           return f"Error generating text response: {e}"

這個類處理一些關(guān)鍵任務(wù)。首先,它使用您的 API 密鑰初始化與 BotHub 的連接(我們之前討論過)。它還設(shè)置一個 UserSession 來跟蹤交互。 generate_prompt 方法接受用戶的請求并將其轉(zhuǎn)換為 API 可以理解的提示。最后,generate_text_response 將提示發(fā)送到 API 并檢索 AI 生成的答案。

流暢且響應(yīng)迅速:GenerateResponseThread

為了避免讓用戶在 AI 思考時等待,我們將使用單獨的線程進行 API 調(diào)用:

import os
import datetime
import json
from dataclasses import dataclass
from typing import List, Dict
from openai import OpenAI
from dotenv import load_dotenv
from PyQt5.QtCore import Qt, QThread, pyqtSignal
from PyQt5.QtGui import QMovie
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QTextEdit, QRadioButton, QButtonGroup, QPushButton, QGroupBox, QListWidget, QListWidgetItem, QTabWidget, QFileDialog, QComboBox, QCheckBox, QMessageBox, QDialogButtonBox, QSpinBox, QFormLayout, QDialog, QDateEdit)

這個GenerateResponseThread基于PyQt5的QThread,在后臺運行API請求,確保用戶界面保持響應(yīng)。

個性化體驗

每個人的學(xué)習(xí)方式都不同。為了滿足個人喜好,我們將創(chuàng)建一個 PreferencesDialog:

@dataclass
class UserRequest:
   query: str
   user_level: str
   preferences: Dict

此對話框允許用戶自定義設(shè)置,例如 AI 的語氣、所需的響應(yīng)長度以及是否包含示例。這種級別的定制可確保更具吸引力和更有效的學(xué)習(xí)體驗。

構(gòu)建界面

最后,讓我們使用 EducationalAssistantGUI 類創(chuàng)建用戶界面:

class UserSession:
   def __init__(self):
       self.history: List[Dict] = []
       self.preferences: Dict = {}
       self.level: str = "beginner"


   def add_to_history(self, query, response):
       self.history.append({"query": query, "response": response, "timestamp": datetime.datetime.now().isoformat()})


   def update_preferences(self, new_preferences):
       self.preferences.update(new_preferences)

此類構(gòu)建主窗口,其中包括兩個選項卡:“聊天”和“歷史記錄”。 “聊天”選項卡允許用戶輸入查詢、選擇級別并查看人工智能的響應(yīng)。 “歷史記錄”選項卡顯示過去的對話,提供搜索和導(dǎo)出功能。

啟動你的人工智能學(xué)習(xí)伙伴

現(xiàn)在,讓我們將我們的創(chuàng)作變?yōu)楝F(xiàn)實:

class EducationalAssistant:
   def __init__(self):
       load_dotenv()
       self.client = OpenAI(api_key=os.getenv('BOTHUB_API_KEY'), base_url='https://bothub.chat/api/v2/openai/v1')
       self.session = UserSession()


   def generate_prompt(self, request):
       prompt = f"""As an educational assistant, provide a response for a {request.user_level} level student.
       Query: {request.query}\n"""


       if request.preferences:
           prompt += "Consider these preferences:\n"
           for key, value in request.preferences.items():
               if key == "response_length":
                   prompt += f"Desired Length: Approximately {value} words\n"
               elif key == "include_examples" and value:
                   prompt += "Include Examples: Yes\n"
               else:
                   prompt += f"{key.capitalize()}: {value}\n"


       prompt += "Please provide a detailed explanation."
       return prompt
   def generate_text_response(self, request):
       try:
           response = self.client.chat.completions.create(
               model="claude-3.5-sonnet", // u can use any model in "Models available" on BotHub
               messages=[
                   {"role": "system", "content": "You are an educational assistant."},
                   {"role": "user", "content": self.generate_prompt(request)}
               ]
           )
           return response.choices[0].message.content
       except Exception as e:
           return f"Error generating text response: {e}"

恭喜!您已經(jīng)構(gòu)建了自己的個性化 AI 學(xué)習(xí)助手。


現(xiàn)在您已經(jīng)有了一個可以運行的應(yīng)用程序,請考慮如何使其變得更好! BotHub API 提供了很大的靈活性。您可以集成圖像生成或語音轉(zhuǎn)錄,而不僅僅是文本響應(yīng)。 BotHub 還允許您訪問多種 AI 模型,讓您可以為不同的任務(wù)選擇最佳的模型。想象一下,您的助手能夠總結(jié)復(fù)雜的主題、翻譯語言,甚至生成練習(xí)測驗!可能性是巨大的。你已經(jīng)打下了堅實的基礎(chǔ);現(xiàn)在就出發(fā)去探索吧!

以上是教程:創(chuàng)建您自己的 AI 學(xué)習(xí)伙伴的詳細內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻,版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

熱門話題

Laravel 教程
1597
29
PHP教程
1488
72
如何處理Python中的API身份驗證 如何處理Python中的API身份驗證 Jul 13, 2025 am 02:22 AM

處理API認證的關(guān)鍵在于理解并正確使用認證方式。1.APIKey是最簡單的認證方式,通常放在請求頭或URL參數(shù)中;2.BasicAuth使用用戶名和密碼進行Base64編碼傳輸,適合內(nèi)部系統(tǒng);3.OAuth2需先通過client_id和client_secret獲取Token,再在請求頭中帶上BearerToken;4.為應(yīng)對Token過期,可封裝Token管理類自動刷新Token;總之,根據(jù)文檔選擇合適方式,并安全存儲密鑰信息是關(guān)鍵。

解釋Python斷言。 解釋Python斷言。 Jul 07, 2025 am 12:14 AM

Assert是Python用于調(diào)試的斷言工具,當(dāng)條件不滿足時拋出AssertionError。其語法為assert條件加可選錯誤信息,適用于內(nèi)部邏輯驗證如參數(shù)檢查、狀態(tài)確認等,但不能用于安全或用戶輸入檢查,且應(yīng)配合清晰提示信息使用,僅限開發(fā)階段輔助調(diào)試而非替代異常處理。

什么是Python迭代器? 什么是Python迭代器? Jul 08, 2025 am 02:56 AM

Inpython,IteratorSareObjectSthallowloopingThroughCollectionsByImplementing_iter __()和__next __()。1)iteratorsWiaTheIteratorProtocol,使用__ITER __()toreTurnterateratoratoranteratoratoranteratoratorAnterAnteratoratorant antheittheext__()

什么是Python型提示? 什么是Python型提示? Jul 07, 2025 am 02:55 AM

typeHintsInpyThonsolverbromblemboyofambiguityandPotentialBugSindyNamalytyCodeByallowingDevelopsosteSpecefectifyExpectedTypes.theyenhancereadability,enablellybugdetection,andimprovetool.typehintsupport.typehintsareadsareadsareadsareadsareadsareadsareadsareadsareaddedusidocolon(

如何一次迭代兩個列表 如何一次迭代兩個列表 Jul 09, 2025 am 01:13 AM

在Python中同時遍歷兩個列表的常用方法是使用zip()函數(shù),它會按順序配對多個列表并以最短為準;若列表長度不一致,可使用itertools.zip_longest()以最長為準并填充缺失值;結(jié)合enumerate()可同時獲取索引。1.zip()簡潔實用,適合成對數(shù)據(jù)迭代;2.zip_longest()處理不一致長度時可填充默認值;3.enumerate(zip())可在遍歷時獲取索引,滿足多種復(fù)雜場景需求。

Python Fastapi教程 Python Fastapi教程 Jul 12, 2025 am 02:42 AM

要使用Python創(chuàng)建現(xiàn)代高效的API,推薦使用FastAPI;其基于標準Python類型提示,可自動生成文檔,性能優(yōu)越。安裝FastAPI和ASGI服務(wù)器uvicorn后,即可編寫接口代碼。通過定義路由、編寫處理函數(shù)并返回數(shù)據(jù),可以快速構(gòu)建API。FastAPI支持多種HTTP方法,并提供自動生成的SwaggerUI和ReDoc文檔系統(tǒng)。URL參數(shù)可通過路徑定義捕獲,查詢參數(shù)則通過函數(shù)參數(shù)設(shè)置默認值實現(xiàn)。合理使用Pydantic模型有助于提升開發(fā)效率和準確性。

如何用Python測試API 如何用Python測試API Jul 12, 2025 am 02:47 AM

要測試API需使用Python的Requests庫,步驟為安裝庫、發(fā)送請求、驗證響應(yīng)、設(shè)置超時與重試。首先通過pipinstallrequests安裝庫;接著用requests.get()或requests.post()等方法發(fā)送GET或POST請求;然后檢查response.status_code和response.json()確保返回結(jié)果符合預(yù)期;最后可添加timeout參數(shù)設(shè)置超時時間,并結(jié)合retrying庫實現(xiàn)自動重試以增強穩(wěn)定性。

設(shè)置并使用Python虛擬環(huán)境 設(shè)置并使用Python虛擬環(huán)境 Jul 06, 2025 am 02:56 AM

虛擬環(huán)境能隔離不同項目的依賴。使用Python自帶的venv模塊創(chuàng)建,命令為python-mvenvenv;激活方式:Windows用env\Scripts\activate,macOS/Linux用sourceenv/bin/activate;安裝包使用pipinstall,生成需求文件用pipfreeze>requirements.txt,恢復(fù)環(huán)境用pipinstall-rrequirements.txt;注意事項包括不提交到Git、每次新開終端需重新激活、可用IDE自動識別切換。

See all articles