🔍 搜尋結果:result

🔍 搜尋結果:result

20 多個使用 AI 的專案,具有完整的源程式碼🚀

過去幾天對於人工智慧來說是令人興奮的。 然而,作為開發人員,我們中的許多人還不了解人工智慧的易用性。 今天,我們將介紹您可以使用人工智慧輕鬆建立的精彩專案。無需成為人工智慧專家,每個工具都附帶教學或程式碼演練。 讓我們跳進去吧! ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0vxxzizvu643bfpbo1xu.gif) --- 1. [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 在數小時內為您的產品提供 AI Copilot。 ------------------------------------------------------------------------------------ [![副駕駛套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzuxjfog2ldam3csrl62.png)](https://github.com/CopilotKit/CopilotKit) 將 AI 功能整合到 React 中是很困難的,這就是 Copilot 的用武之地。一個簡單快速的解決方案,可將可投入生產的 Copilot 整合到任何產品中! 您可以使用兩個 React 元件將關鍵 AI 功能整合到 React 應用程式中。它們還提供內建(完全可自訂)Copilot 原生 UX 元件,例如`<CopilotKit />` 、 `<CopilotPopup />` 、 `<CopilotSidebar />` 、 `<CopilotTextarea />` 。 開始使用以下 npm 指令。 ``` npm i @copilotkit/react-core @copilotkit/react-ui ``` Copilot Portal 是 CopilotKit 提供的元件之一,CopilotKit 是一個應用程式內人工智慧聊天機器人,可查看目前應用狀態並在應用程式內採取操作。它透過插件與應用程式前端和後端以及第三方服務進行通訊。 這就是整合聊天機器人的方法。 `CopilotKit`必須包裝與 CopilotKit 互動的所有元件。建議您也開始使用`CopilotSidebar` (您可以稍後切換到不同的 UI 提供者)。 ``` "use client"; import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import "@copilotkit/react-ui/styles.css"; export default function RootLayout({children}) { return ( <CopilotKit url="/path_to_copilotkit_endpoint/see_below"> <CopilotSidebar> {children} </CopilotSidebar> </CopilotKit> ); } ``` 您可以使用此[快速入門指南](https://docs.copilotkit.ai/getting-started/quickstart-backend)設定 Copilot 後端端點。 之後,您可以讓 Copilot 採取行動。您可以閱讀如何提供[外部上下文](https://docs.copilotkit.ai/getting-started/quickstart-chatbot#provide-context)。您可以使用`useMakeCopilotReadable`和`useMakeCopilotDocumentReadable`反應掛鉤來執行此操作。 ``` "use client"; import { useMakeCopilotActionable } from '@copilotkit/react-core'; // Let the copilot take action on behalf of the user. useMakeCopilotActionable( { name: "setEmployeesAsSelected", // no spaces allowed in the function name description: "Set the given employees as 'selected'", argumentAnnotations: [ { name: "employeeIds", type: "array", items: { type: "string" } description: "The IDs of employees to set as selected", required: true } ], implementation: async (employeeIds) => setEmployeesAsSelected(employeeIds), }, [] ); ``` 您可以閱讀[文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea)並查看[演示影片](https://github.com/CopilotKit/CopilotKit?tab=readme-ov-file#demo)。 您可以輕鬆整合 Vercel AI SDK、OpenAI API、Langchain 和其他 LLM 供應商。您可以按照本[指南](https://docs.copilotkit.ai/getting-started/quickstart-chatbot)將聊天機器人整合到您的應用程式中。 基本想法是非常快速地建立人工智慧聊天機器人,而無需在製作任何基於法學碩士的應用程式時費力。 用例是巨大的,作為開發人員,我們絕對應該在下一個專案中嘗試使用 CopilotKit。 CopilotKit 在 GitHub 上擁有超過 5800 顆星,發布了 200 多個版本,這意味著它們不斷改進。 ![明星副駕駛套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p8i6roafbjxvds26fl35.gif) {% cta https://go.copilotkit.ai/Anmol %} Star CopilotKit ⭐️ {% endcta %} --- ### 🎯 使用 CopilotKit 建立的熱門應用程式。 我們可以使用 CopilotKit 建立許多創新應用程式,所以讓我們探索一些脫穎而出的應用程式! ### ✅ [人工智慧驅動的部落格平台](https://dev.to/copilotkit/how-to-build-an-ai-powered-blogging-platform-nextjs-langchain-supabase-1hdp)。 ![部落格平台](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tvx995v2lvyujnsavaxx.gif) 您可以閱讀本文,使用`Next.js` 、 `Langchain` 、 `Supabase`和`CopilotKit`來建立這個令人驚嘆的應用程式。 LangChain&Tavily用作網路搜尋人工智慧代理,Supabase用於儲存和檢索部落格平台文章資料,CopilotKit用於將人工智慧整合到應用程式中。 ![演示人工智慧部落格平台](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/88ni6x3pdno43vani7q9.png) 您可以檢查[GitHub 儲存庫](https://github.com/TheGreatBonnie/aipoweredblog)。 ### ✅ [V0.dev 複製](https://dev.to/copilotkit/i-created-a-v0-clone-with-nextjs-gpt4-copilotkit-3cmb)。 ![v0](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pyutbegrv571lp3i6081.png) 如果您不熟悉,Vercel 的 V0 是一款人工智慧驅動的工具,可讓您根據提示產生 UI,以及許多其他有用的功能。 shadcn 元件現在可以在文件本身的 v0 中進行編輯(如其網站所示)。 ![v0 開發](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/951hk0jqrioboe4jxf5i.gif) 您可以使用`Next.js` 、 `GPT4`和`CopilotKit`建立 V0 的克隆。這個詳細的教程名列前 7 名,總的來說,這是一個值得加入到您的作品集中的偉大專案。 簽名頁的產生輸出如下所示。 ![簽名頁](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8xu1l5el91x4w62sz7kh.png) 您可以透過點擊右上角的按鈕輕鬆在`React Code`和`UI`之間切換。這麼酷的概念! 您可以檢查[GitHub 儲存庫](https://github.com/Tabintel/v0-copilot-next)。 ### ✅ [人工智慧行銷經理](https://dev.to/copilotkit/build-an-ai-powered-campaign-manager-nextjs-openai-copilotkit-59ii)。 ![競選經理](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/moytsjm7lcq1g52sn0ot.gif) 您可以使用`Next.js` 、 `OpenAI` 、 `Radix UI` (用於實現可存取性)、 `Recharts` (用於建立互動式圖表)以及`CopilotKit`來建立這個出色的專案來閱讀本文。 您可以觀看 David 的示範! {% 嵌入 https://youtu.be/gCJpH6Tnj5g %} 如果你想用更少的錢學到更多,這是我最喜歡的一個。 我喜歡它的 UI(一般教學不是這樣),這正是它成為你的編碼清單上的一個乾淨專案的原因:) ![示範動圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gt14n0xn3bekl7u5uib1.gif) 您可以查看該應用程式的[現場演示](https://campaign-manager-demo.vercel.app/)。 您可以檢查[GitHub 儲存庫](https://github.com/CopilotKit/campaign-manager-demo)。 ### ✅ [附有人工智慧副駕駛的電子表格應用程式](https://dev.to/copilotkit/build-an-ai-powered-spreadsheet-app-nextjs-langchain-copilotkit-109d)。 ![電子表格應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gexhqf0alwmwguu7kqsv.gif) 您可以閱讀本文,使用`Next.js` 、 `GPT-4` 、 `LangChain`和`CopilotKit`來建立這個很棒的工具。 為了使工作更輕鬆,它使用[React Spreadsheet](https://github.com/iddan/react-spreadsheet)套件為 React 和[Tavily AI](https://tavily.com/)建立簡單的可自訂電子表格作為搜尋引擎,使 AI 代理能夠進行研究並存取即時知識 你可以觀看這個演示! {% 嵌入 https://www.youtube.com/watch?v=kGQ9xl5mSoQ %} 您也可以查看[現場演示](https://spreadsheet-demo-tau.vercel.app/)。我可以肯定地說,這是一個獨特的案例,你可以得到很多啟發。 您可以檢查[GitHub 儲存庫](https://github.com/CopilotKit/spreadsheet-demo)。 ### ✅[與您的履歷聊天](https://dev.to/copilotkit/how-to-build-the-with-nextjs-openai-1mhb)。 ![與履歷聊天](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gdagmyn1tvoa2lwfoqto.gif) 您可以閱讀本文,使用`Next.js` 、 `OpenAI`和`CopilotKit`來建立這個很棒的用例。 您不僅可以使用 ChatGPT 產生履歷,還可以將其匯出為 PDF,甚至可以透過與其對話來進一步改進它。多酷啊,對吧:) ![簡歷聊天演示](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x6j27yls99cdv219ztwx.png) 您可以檢查[GitHub 儲存庫](https://github.com/TheGreatBonnie/AIPoweredResumeBuilder)。 ### ✅ [文字到 Powerpoint 應用程式](https://dev.to/copilotkit/how-to-build-ai-powered-powerpoint-app-nextjs-openai-copilotkit-ji2)。 ![文字到 Powerpoint 應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vh01hh3l29qtztri4180.png) 您可以閱讀本文,使用`Next.js` 、 `OpenAI`和`CopilotKit`建立 Text to Powerpoint 應用程式。 這是一個簡單但非常強大的概念,本文也清楚地說明如何在任何幻燈中加入背景圖像。 您可以檢查[GitHub 儲存庫](https://github.com/TheGreatBonnie/aipoweredpresentation)。 ### ✅ [StudyPal:您的人工智慧驅動的個人化學習伴侶](https://dev.to/rajesh-adk-137/studypal-your-ai-powered-personalized-learning-companion-59d)。 ![學習夥伴](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qhau3p28cylr25lae5r4.png) 您可以從精選清單中選擇您想要的主題,為個人化的學習旅程奠定基礎。 您需要提供有關您的教育背景的詳細訊息,以便 StudyPal 能夠根據他們當前的知識水平定製材料和練習。 `Additional Details`部分可讓學生指定重點領域,確保內容與其學習目標一致。 您可以閱讀本文,使用`React` 、 `Node`和`CopilotKit`來建立這個很棒的用例。 您可以觀看該應用程式的[演示](https://github-production-user-asset-6210df.s3.amazonaws.com/89499267/328419789-a06b11c6-ffbc-44b6-96b0-648d2a38cd7c.mp4?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAVCODYLSA53PQK4ZA%2F20240512%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240512T083208Z&X-Amz-Expires=300&X-Amz-Signature=f6fe016e65e167e94b8322b70743a7fb02fed91f2c87c5af7459e1fa022faac2&X-Amz-SignedHeaders=host&actor_id=74038190&key_id=0&repo_id=793889064)。 您可以檢查[GitHub 儲存庫](https://github.com/rajesh-adk-137/StudyPal)。 --- 2.什麼是郎鏈? -------- 其餘專案將與 langchain 和 AI 相關(有些使用 python)。最好稍微了解一下這一點。 LangChain 是用於開發由大型語言模型(LLM)支援的應用程式的框架。 ![朗查恩](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fuo9c2ljruv3c54is10.png) ![朗查恩](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/btgq9o8y1yhjfnrinqqn.png) 總體而言,LangChain 簡化了 LLM 申請生命週期的每個階段。您可以閱讀[官方文件](https://python.langchain.com/docs/get_started/introduction/)以了解更多內容。 如果您想了解有關 langchain 的更多訊息,我建議您觀看 freeCodeCamp 的[本教程](https://www.youtube.com/watch?v=HSZ_uaif57o)。 {% 嵌入 https://www.youtube.com/watch?v=HSZ\_uaif57o %} --- ### 🎯 使用 Langchain/AI/Python 建立的熱門應用程式。 我們可以使用 langchain 建立很多很多高級應用程式,所以讓我們探索一些脫穎而出的應用程式! ### ✅ [Mac 上的語音助理](https://github.com/chidiwilliams/GPT-Automator)- 您的語音控制 Mac 助理。 ![GPT自動機](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rdzv06jnr3z33s7qll5k.png) 您的語音控制 Mac 助理。 GPT Automator 可讓您使用語音在 Mac 上執行任務。例如,打開應用程式、尋找餐廳、綜合資訊。太棒了:D 它是在倫敦黑客馬拉松期間建構的。 它有兩個主要部分: A。語音命令:它使用本地執行的 Whisper(Buzz 的一個分支)來產生命令。 b.命令到行動:您向配備了我們編寫的自訂工具的 LangChain 代理程式發出命令。這些工具包括使用 AppleScript 控制電腦的作業系統以及使用 JavaScript 控制活動瀏覽器。最後,就像任何優秀的人工智慧一樣,我們讓代理商使用 AppleScript 說出最終結果「{Result}」(如果您以前沒有使用過,請嘗試在 Mac 終端機中輸入「Hello World!」)。 我們製作了一個自訂工具,讓法學碩士使用 AppleScript 控制電腦。提示符是文件字串: ``` @tool def computer_applescript_action(apple_script): """ Use this when you want to execute a command on the computer. The command should be in AppleScript. Here are some examples of good AppleScript commands: Command: Create a new page in Notion AppleScript: tell application "Notion" activate delay 0.5 tell application "System Events" to keystroke "n" using {{command down}} end tell ... Write the AppleScript for the Command: Command: """ p = subprocess.Popen(['osascript', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate(applescript.encode('utf-8')) if p.returncode != 0: raise Exception(stderr) decoded_text = stdout.decode("utf-8") return decoded_text ``` 如果您想知道它是如何運作的,GPT Automator 使用 OpenAI 的 Whisper 將您的音訊輸入轉換為文字。然後,它使用LangChain Agent 選擇一組操作,包括使用OpenAI 的GPT-3(“text-davinci-003”)從提示符號產生AppleScript(用於桌面自動化)和JavaScript(用於瀏覽器自動化)命令,然後執行產生的腳本。 請記住,這不適用於生產用途。該專案執行從自然語言產生的程式碼,可能容易受到提示注入和類似的攻擊。這項工作是作為概念驗證而進行的。 您可以閱讀[安裝指南](https://github.com/chidiwilliams/GPT-Automator?tab=readme-ov-file#instructions)。 讓我們看看一些提示及其作用: ⚡ 求計算結果。 > 提示:“2 + 2 是什麼?” 它將編寫 AppleScript 開啟計算器並輸入 5 \* 5。 ⚡ 尋找附近的餐廳。 > 提示:“查找我附近的餐廳” 它將打開 Chrome,谷歌搜尋附近的餐廳,解析頁面,然後返回最上面的結果。有時它很厚顏無恥,反而會打開谷歌地圖結果並說「最好的餐廳是谷歌地圖頁面頂部的餐廳」。其他時候,它會打開 Google 上的頂部連結 - 並卡在 Google 可存取性頁面上... 以下是執行時列印到終端的內容: ``` Command: Find a great restaurant near Manchester. > Entering new AgentExecutor chain... I need to search for a restaurant near Manchester. Action: chrome_open_url Action Input: https://www.google.com/search?q=restaurant+near+Manchester Observation: Thought: I need to read the page Action: chrome_read_the_page Action Input: Observation: Accessibility links Skip to main content ... # Shortned for brevity Dishoom Manchester 4.7 (3.3K) · £££ · Indian 32 Bridge St · Near John Rylands Library Closes soon ⋅ 11 pm Stylish eatery for modern Indian fare San Carlo 4.2 (2.8K) · £££ · Italian 42 King St W · Near John Rylands Library Closes soon ⋅ 11 pm Posh, sceney Italian restaurant Turtle Bay Manchester Northern Quarter 4.7 Thought: I now know the final answer Final Answer: The 15 best restaurants in Manchester include El Gato Negro, Albert's Schloss, The Refuge, Hawksmoor, On The Hush, Dishoom, Banyan, Zouk Tea Room & Grill, Edison Bar, MyLahore Manchester, Turtle Bay Manchester Northern Quarter, San Carlo, The Black Friar, Mana, and Tast Cuina Catalana. ``` 我不能保證這些餐廳值得,請自行承擔風險。哈哈! ⚡ 如果您要求 GPT Automator 擦除您的計算機,它會的。 是的,如果您要求的話,它會擦除您的電腦! 我內心的自我尖叫著要這麼做:) 您可以在這裡查看完整的演示! {% 嵌入 https://www.loom.com/share/7bfa82c604f3412fbbb04191ce2ae12f %} 您可以在[Chidi 的部落格](https://chidiwilliams.com/posts/gpt-automator)上閱讀更多內容。 它更像是一個業餘專案,因此他們在 GitHub 上有大約 200 個 star,但它非常酷。 您可以檢查[GitHub 儲存庫](https://github.com/chidiwilliams/GPT-Automator)。 ✅ [Instrukt](https://github.com/blob42/Instrukt) - 終端中整合人工智慧。 ------------------------------------------------------------- ![指示](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wsk64pf5yuosui91tmz9.png) Instrukt是一個基於終端的AI整合環境。它提供了一個平台,用戶可以: - 建立並指導模組化人工智慧代理。 - 產生問答的文件索引。 - 建立工具並將其附加到任何代理程式。 用自然語言指導它們,並且為了安全起見,在安全容器(目前使用 Docker 實作)中執行它們,以在其專用的沙盒空間中執行任務。 使用`Langchain` 、 `Textual`和`Chroma`建構。 開始使用以下命令。 ``` pip install instrukt[all] ``` ![指示](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r3aza7hnlji7hbi2o0js.gif) 有許多令人興奮的功能,例如: - 基於終端的介面,讓強力鍵盤使用者無需離開鍵盤即可指示 AI 代理。 - 對您的資料建立索引並讓代理程式檢索它以進行問答。您可以使用簡單的 UI 建立和組織索引。 - 索引建立將自動偵測程式語言並相應地優化拆分/分塊策略。 - 在安全的 Docker 容器內執行代理程式以確保安全和隱私。 - 整合的 REPL-Prompt 可實現與代理程式的快速交互,以及用於開發和測試的快速回饋循環。 - 您可以使用自訂命令自動執行重複任務。它還具有內建的提示/聊天歷史記錄。 您可以閱讀有關所有[功能的](https://github.com/blob42/Instrukt?tab=readme-ov-file#features)資訊。 您可以閱讀[安裝指南](https://blob42.github.io/Instrukt/install.html)。 您還可以使用內建的 IPython 控制台來除錯和內省代理,這是一個簡潔的小功能。 ![控制台除錯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qaan8np68e3fk1yueexm.png) Instrukt 已獲得 AGPL 許可證,這意味著任何人都可以將其用於任何目的。 可以肯定地說,Instrukt 是您觸手可及的終端人工智慧指揮官。 這是一個新專案,因此他們在 GitHub 上有大約 200 多顆星,但用例非常好。 您可以檢查[GitHub 儲存庫](https://github.com/blob42/Instrukt)。 ✅ [ChatFiles](https://github.com/guangzhengli/ChatFiles) - 上傳您的檔案並與其對話。 ----------------------------------------------------------------------- ![聊天文件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lhimajsma8ijyzeknmlg.png) 文件聊天機器人 — 多個文件,由 GPT / Embedding 提供支援。你可以上傳任何文件並與之對話,考慮到他們使用了另一個著名的開源專案,UI 非常好。 它在底層使用 Langchain 和[Chatbot-ui](https://github.com/mckaywrigley/chatbot-ui) 。使用 Nextjs、TypeScript、Tailwind 和 Supabase(向量 DB)建構。 如果您想了解該方法和技術架構,那麼就在這裡! ![建築學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8zbn7h50k6gwxgz6rkaf.png) 此環境僅用於試用,支援最大檔案大小為 10 MB,這是一個缺點,如果您想要更大的大小,則可以[在本機安裝](https://github.com/guangzhengli/ChatFiles?tab=readme-ov-file#how-to-run-locally)。 他們提供了您可以使用的[入門問題](https://github.com/guangzhengli/ChatFiles/blob/main/doc/Example.md)。您可以查看[現場演示](https://chatfile.vectorhub.org/)。 他們在 GitHub 上有 3k star,並且發布了`v0.3`版本。 您可以檢查[GitHub 儲存庫](https://github.com/guangzhengli/ChatFiles)。 ✅ [具有多代理協作的終極人工智慧自動化 - LangGraph + GPT 研究人員](https://blog.langchain.dev/how-to-build-the-ultimate-ai-automation-with-multi-agent-collaboration/)。 ------------------------------------------------------------------------------------------------------------------------------------------------- LangGraph 是一個使用 LLM 建立有狀態、多參與者應用程式的函式庫。此範例使用 Langgraph 自動化對任何給定主題的深入研究過程。 簡而言之,這個範例展示了人工智慧代理團隊如何協同工作,對給定主題進行從規劃到發布的研究。此範例還將利用領先的自主研究代理[GPT Researcher](https://github.com/assafelovic/gpt-researcher) ,我已在過去的一篇文章中介紹過該代理。 研究團隊由七名法學碩士代理人: ⚡ `Chief Editor` - 監督研究過程並管理團隊。這是使用 LangGraph 協調其他代理程式的「主」代理程式。該代理充當主要的 LangGraph 介面。 ⚡ `GPT Researcher` - 專門的自主代理,對給定主題進行深入研究。 ⚡ `Editor` - 負責規劃研究大綱和結構。 ⚡ `Reviewer` - 根據一組標準驗證研究結果的正確性。 ⚡ `Reviser` - 根據審查者的回饋修改研究結果。 ⚡ `Writer` - 負責編譯和撰寫最終報告。 ⚡ `Publisher` - 負責以各種格式發布最終報告。 自動化過程基於以下階段(架構),文章中清楚地顯示了這一點。 - 策劃階段。 - 資料收集和分析。 - 審查和修訂。 - 寫作並提交。 - 出版品. ![建築學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zwpvlf859m9c6v8mttxk.png) 您可以閱讀有關正在發生的事情的[詳細步驟文件](https://github.com/assafelovic/gpt-researcher/tree/master/multi_agents?ref=blog.langchain.dev#steps)。 助手的最終運作將產生 Markdown、PDF 和 Docx 等格式的最終研究報告。 您可以閱讀這篇文章,其中介紹[如何透過多代理協作來建立終極人工智慧自動化](https://blog.langchain.dev/how-to-build-the-ultimate-ai-automation-with-multi-agent-collaboration/),其中 Wix 研發主管 Assaf Elovic 介紹如何使用 LangGraph 與專業代理團隊建立自主研究助理。它具有易於理解的程式碼範例,並清楚地說明正在發生的事情。開發者必讀! 最好的部分是,如果您想更改研究查詢並自訂報告,只需編輯主目錄中的`task.json`檔案。真的很棒:) 它由 GPT 研究人員負責,擁有 10k 顆星,但自從上次提交是在幾天前以來,它經常更新。 您可以檢查[GitHub 儲存庫](https://github.com/assafelovic/gpt-researcher/tree/master/multi_agents)。 ✅[僚機AI](https://github.com/e-johnstonn/wingmanAI) 。 --------------------------------------------------- ![僚機人工智慧](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ortnj43j63gx4riqvl4x.png) WingmanAI 是一款功能強大的工具,可與系統和麥克風音訊的即時轉錄進行互動。 它使用 ChatGPT,讓您與文字記錄即時交互,作為機器人的廣泛記憶體基礎,提供獨特的通訊平台。 當您載入指定人員的文字記錄時,機器人甚至可以回答有關過去對話的問題。 所有精彩功能的詳細介紹: ⚡ 它可以轉錄系統輸出和麥克風輸入音頻,讓您以易於閱讀的格式查看即時轉錄。 ⚡ 機器人以令牌有效的方式維護對話記錄,因為只有當前的文字區塊會傳遞給機器人。 ⚡ 您可以與 ChatGPT 支援的機器人聊天,機器人會即時讀取您的文字記錄。 ⚡ 您可以繼續附加到已儲存的記錄中,隨著時間的推移建立一個龐大的資料庫供機器人從中提取。 ⚡ 它允許您保存成績單以供將來使用。您可以稍後隨時加載它們,並且對機器人進行的任何查詢都將與保存的轉錄本的向量資料庫交叉引用,從而為機器人提供更豐富的上下文。 您可以閱讀[安裝說明](https://github.com/e-johnstonn/wingmanAI?tab=readme-ov-file#installation)。 您只需將 OpenAI API 金鑰放入`keys.env`檔案中並執行`main.py` 。 唯一的缺點是該應用程式目前僅與 Windows 相容。 Windows 用戶現在更高興了:) 您可以觀看[完整的示範影片](https://github.com/e-johnstonn/wingmanAI?tab=readme-ov-file#demo)。由於限制,下面所附的 gif 很短(86 秒中只有 30 秒)。 ![30 秒演示 gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gmosnsbwkkb76q83y46i.gif) 我對這個概念感到非常驚訝,因為我從來沒有想過它可以以這種方式實現。當開發人員用非常簡單的概念創造出一些很酷的東西時,感覺真的很棒:) 它在 GitHub 上有 420 多顆星,並且不再維護。但你可以用它來建造更好的東西。 您可以檢查[GitHub 儲存庫](https://github.com/e-johnstonn/wingmanAI)。 ✅[考試](https://github.com/codeacme17/examor)。 -------------------------------------------- ![前愛](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x4fh09yrwhnalr1oxgv4.png) 一款允許您根據知識筆記參加考試的應用程式。它可以讓您專注於您所學和所寫的內容🧠。 它不斷提示您提出問題以複習筆記內容,這對於學生、學者、受訪者和終身學習者非常有用。 專案管理員正在使用 next.js 重構專案,這對於使用`next.js`開發人員來說非常好。 讓我們來詳細分析一下一些很棒的功能: ⚡ 建立筆記時可以上傳相關文件。該應用程式根據這些文件的內容產生一組問題。這些問題將在未來呈現給大家。建立筆記時,您作為使用者還可以選擇要產生的問題類型。 ![問題選擇](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rp5seq1zpotaxej6dj6l.png) ⚡ 收到每日問題後,您可以提供答案。 GPT 將評分、驗證並提供正確答案。透過評估答案和連結文件的正確性來確定分數(0 ~ 10 分)。這個分數會影響隨後的艾賓浩斯評審過程。將會在未來的發布版本中進行最佳化。 ⚡ 角色可以為問題產生和評估提供更多可能性。您可以在設定頁面上設定角色。有關各種角色的更多訊息,建議參閱詳細的[角色手冊指南](https://github.com/codeacme17/examor/blob/main/docs/en-role.md)。 ![角色選擇](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n0zdohzkowcdrdnxjzba.png) ⚡ 練習問題時,可以用不同的方法作答。下圖顯示了單選題的範例。 ![回答問題](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yzg8vvuxndhw9v2s1x8c.png) ⚡ 它有一個包含多個[模組](https://github.com/codeacme17/examor?tab=readme-ov-file#-modules)的列表,例如`Examine` 、 `Note` 、 `Notes Management`和`Random Question`使用這些模組您可以在筆記中導入問題,刪除或加入新文件到上傳的筆記中,等等。 我喜歡整個概念,這會引起任何曾經面臨過修改筆記問題的人的注意。 您可以閱讀包含如何正確使用它的詳細指南的[文件](https://github.com/codeacme17/examor/blob/main/README.md)。 它在 GitHub 上有 1k star,目前版本為`v0.4.2` 。 您可以檢查[GitHub 儲存庫](https://github.com/codeacme17/examor)。 ✅[語音GPT](https://github.com/hahahumble/speechgpt) 。 --------------------------------------------------- ![語音GPT](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/on0exhy65owc13tzue0v.png) ![語音GPT](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4rrge2nyhowtcdyd3gi5.png) SpeechGPT 是一個 Web 應用程式,可讓您與 ChatGPT 進行對話。 您可以利用此應用程式來提高您的語言技能,或只是透過 ChatGPT 享受聊天的樂趣。 大多數人會說這有什麼獨特之處,但事實確實如此。 讓我們來打破一些很棒的功能: ⚡ 所有資料儲存在本地,隱私性更強。 ⚡ 根據文件,它支援 100 多種語言,但我在現場演示中只能看到對三種語言的支援。 ![語言](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g6e7jsrhmvrdlidyvnho.png) ⚡ 包含內建語音辨識以及與 Azure 語音服務的整合。 ![語音辨識](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gr2vsaymy50wtiperprd.png) ⚡ 包含內建語音合成,以及與 Amazon Polly 和 Azure 語音服務的整合。 ![語音合成](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2m3kp9othpa9rbb4it57.png) 請按照[文件中的教學](https://github.com/hahahumble/speechgpt?tab=readme-ov-file#-tutorial)了解如何使用它。 您可以在[speechgpt.app](https://speechgpt.app/)上觀看現場演示。這是一個完美的例子,說明了一些額外的功能如何將您的應用程式提升到一個新的水平! SpeechGPT 在 GitHub 上有 2700 顆星,目前版本為`v0.5.1` 。 您可以檢查[GitHub 儲存庫](https://github.com/hahahumble/speechgpt)。 ✅ [myGPTReader](https://github.com/madawei2699/myGPTReader) - 閱讀並與 AI 機器人聊天。 ---------------------------------------------------------------------------- ![我的GPT閱讀器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58doii8daomf54te5eca.png) myGPTReader 是 Slack 上的機器人,可以閱讀和總結任何網頁、文件(包括電子書),甚至來自 YouTube 的影片。它可以透過語音與您交流。 一些有價值的功能是: ⚡ 使用 myGPTReader 透過對話快速閱讀和理解任何網頁內容,甚至是影片(目前僅支援帶有字幕的 YouTube 影片)。 ![讀者](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x626mtnvqr5vw43938iw.gif) ⚡ 使用 myGPTReader 快速閱讀任何文件的內容,支援電子書、PDF、DOCX、TXT 和 Markdown。 ![文件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5am7njxco7vhronuirgu.gif) ⚡ 透過與 myGPTReader 語音對話來練習外語,它可以成為您的私人導師,支援中文、英語、德語和日語。 ![嗓音](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/40pzlgtuhcyxgwa1z2gs.gif) ⚡ 內建大量提示模板,使用它們可以更好地與chatGPT對話。 ![問](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ehgn218hwewzeft98xkp.gif) ⚡ myGPTReader 每天發送最新熱點新聞,並自動產生摘要,讓您快速了解今日熱點。 您可以造訪[官方網站](https://www.myreader.io/)。 您可以加入擁有超過 5000 名會員的儲存庫上的 Slack 頻道,免費體驗所有這些功能。 它們在 GitHub 上有 4.4k 顆星,並且像此列表中的其他專案一樣使用 Python 建置。 您可以檢查[GitHub 儲存庫](https://github.com/madawei2699/myGPTReader)。 ✅ [RepoChat](https://github.com/pnkvalavala/repochat) - 支援 GitHub 儲存庫互動的聊天機器人助理。 -------------------------------------------------------------------------------- ![重新聊天](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3gf9bjn2a47f1t43aiju.png) Repochat 是一個互動式聊天機器人專案,旨在使用大型語言模型 (LLM) 參與有關 GitHub 儲存庫的對話。 它允許用戶進行有意義的討論、提出問題並從 GitHub 儲存庫檢索相關資訊。本自述文件提供了在本機電腦上設定和使用 Repochat 的逐步說明。 他們建立了兩個具有不同功能的分支,這對我來說有點新鮮。 ⚡ Repochat 的主要分支被設計為完全在本機上執行。此版本的 Repochat 不依賴外部 API 呼叫,並且可以更好地控制您的資料和處理。如果您正在尋找獨立的解決方案,那麼主分支就是您的最佳選擇。 ⚡ Repochat 的雲端分支主要依賴對外部服務的 API 呼叫來進行模型推理和儲存。它非常適合那些喜歡基於雲端的解決方案並且不想設定本地環境的人。 您可以閱讀[安裝說明](https://github.com/pnkvalavala/repochat?tab=readme-ov-file#installation)。 Repochat 讓您與聊天機器人進行對話。您可以提出問題或提供輸入,聊天機器人將從向量資料庫中檢索相關文件。 然後,它將您的輸入以及檢索到的文件傳送到語言模型以產生回應。 預設情況下,我已將模型設為`codellama-7b-instruct` ,但您可以根據計算機的速度更改它,甚至可以嘗試 13b 量化模型進行回應。 聊天機器人在對話過程中保留記憶以提供上下文相關的回應。 您可以查看[即時網站](https://repochat.streamlit.app/),您可以使用 API 金鑰進行檢查。 你可以觀看這個演示! ![示範](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o7ndxqpwkkww4f5qudiq.gif) 如果您想查看的話,我找到了另一種[選擇](https://github.com/peterw/Chat-with-Github-Repo)。 Repochat 擁有 200 多顆星,並部署在 Streamlit 上。 您可以檢查[GitHub 儲存庫](https://github.com/pnkvalavala/repochat)。 ✅ [NextChat - ChatGPT Next Web](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web) 。 ------------------------------------------------------------------------------------- ![下次聊天](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lnuqjkfcyz8z7kejgbb1.png) 這不是一個典型的副專案,因為程式碼庫足夠大,但值得一看作為靈感。 您只需一鍵即可獲得精心設計的跨平台 ChatGPT Web UI,支援 GPT3、GPT4 和 Gemini Pro(Web / PWA / Linux / Win / MacOS)。 一些很棒的功能是: ⚡ 隱私 首先,所有資料都儲存在瀏覽器本地。 ⚡ 首屏載入速度快(~100kb),支援串流響應。 ⚡ 自動壓縮聊天歷史記錄以支援長時間對話,同時儲存您的代幣。 ⚡ Linux/Windows/MacOS 上的緊湊型用戶端 (~5MB)。 ⚡ 您只需在 Vercel 上一鍵點擊即可在 1 分鐘內免費部署。 ⚡ 與自行部署的法學碩士完全相容。 ⚡ Markdown 支援:LaTex、mermaid、程式碼高亮等。 ![下次聊天](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2uvdfwz1rgy1l2l4pb9p.png) 您可以查看 NextChat 的[現場演示](https://app.nextchat.dev/)和[文件,](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web?tab=readme-ov-file#roadmap)其中包括所有環境變數(主要是 API 金鑰)的清單。 ![下次聊天](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fqykjwgjf35khapdfu20.png) 在本地處理它並不難,他們還提供了 GitHub 操作工作流程,每小時都會自動更新。 NextChat 在 GitHub 上擁有 69k+ 顆星,目前已發布`v2.2`版本。 您可以檢查[GitHub 儲存庫](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web)。 --- 如果您喜歡觀看教程來建立專案,我有一些很好的建議。 🎯 [LangChain GEN AI 教學 – 使用 OpenAI、Google Gemini Pro、LLAMA2 的 6 個端到端專案](https://www.youtube.com/watch?v=x0AnCE9SE4A)– 4 小時。 本教學涵蓋的專案: ✅ LangChain 速成課程 - 打下基礎。 ✅ 使用 Langchain 和 Astradb 與 PDF 聊天。 ✅ 使用 Llama 2 LLM 模型產生部落格。 ✅ 使用 Pinecone VectorDB 的端到端法學碩士課程。 ✅ Google Gemini 專業版示範。 ✅ 多語言發票提取器 LLM 專案。 ✅ 使用 Gemini Pro API 的對話式問答聊天機器人。 {% 嵌入 https://www.youtube.com/watch?v=x0AnCE9SE4A %} 🎯 Streamlit 的 LangChain 速成課程。 本教學涵蓋的專案: ✅ 發票資料提取器。 ✅ 針對自訂資料的基本 QA。 ✅ 總結和有用的鏈類型。 ✅ WordPress 程式碼助理。 ✅ 將語音備忘錄轉換為文字。 你可以找到[速成課程](https://learnlangchain.streamlit.app/)。側邊欄中將有一個關於實踐專案的部分! --- 這麼多很棒的專案:) 但說實話,我見過很多開發人員建立相同的應用程式,您可以獲得無限的靈感。我希望你喜歡這個。 繼續,保存它,並建造每一個,以展示誰是技術老大! 讓我知道哪個專案最讓你驚訝。 祝你有美好的一天!直到下一次。 |如果你喜歡這類東西, 請關注我以了解更多:) | [![用戶名 Anmol_Codes 的 Twitter 個人資料](https://img.shields.io/badge/Twitter-d5d5d5?style=for-the-badge&logo=x&logoColor=0A0209)](https://twitter.com/Anmol_Codes) [![用戶名 Anmol-Baranwal 的 GitHub 個人資料](https://img.shields.io/badge/github-181717?style=for-the-badge&logo=github&logoColor=white)](https://github.com/Anmol-Baranwal) [![用戶名 Anmol-Baranwal 的 LinkedIn 個人資料](https://img.shields.io/badge/LinkedIn-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/Anmol-Baranwal/) | |------------|----------| 請關注 Copilotkit 以獲取更多此類內容。 {% 嵌入 https://dev.to/copilotkit %} --- 原文出處:https://dev.to/copilotkit/20-projects-you-can-build-with-ai-today-352k

Array.reduce() 已被山羊化 🐐✨

標題說明了一切🐐。我想談談我一直以來最喜歡的 JavaScript 陣列方法: **Array.reduce()** 。我知道有很多競爭者,但請聽我說完。 reduce() 不只是一個方法;這是一種生活方式✨。 我不想撒謊,當我第一次開始並發現reduce 時,它有點令人生畏。我花了一段時間才在程式碼中自信地使用它。但當我這麼做的時候,遊戲規則就改變了。突然間,我可以輕鬆地對陣列執行複雜的操作,將它們轉換為我需要的任何內容。我的程式碼變得更快更乾淨。 但不要只相信我的話。讓我向您展示使用reduce() 可以實現的一些功能。是時候深入研究 Array.reduce() 並發現為什麼它絕對是山羊了! 🐐 Array.reduce() 的 9 個用例 🐐 ------------------------ ### 用例 1:對數字求和 reduce() 最直接的用例之一是對一堆數字求和。假設您有一個整數陣列,並且您想要找到總和。 ``` const numbers: number[] = [1, 2, 3, 4, 5]; const sum: number = numbers.reduce((acc, curr) => acc + curr, 0); console.log(sum); // Output: 15 ``` 繁榮!只需一行程式碼,您就可以計算出陣列中所有元素的總和。累加器的初始值設為 0,並且在每次迭代中,我們將當前元素新增至累加器。 \*\* 獎勵:如果您選擇忽略起始值,reduce 將只使用陣列中的第一項。不過我傾向於總是包含一個初始值,這樣比較容易閱讀。 ### 用例 2:展平陣列 您是否曾經發現自己有一個陣列陣列並想:“我希望我可以將其扁平化為一個陣列”? ``` const nestedArray: number[][] = [[1, 2], [3, 4], [5, 6]]; const flattenedArray: number[] = nestedArray.reduce((acc, curr) => acc.concat(curr), []); console.log(flattenedArray); // Output: [1, 2, 3, 4, 5, 6] ``` 在此範例中,我們從一個空陣列開始作為初始累加器值。然後,在每次迭代中,我們使用 concat() 方法將目前子陣列連接到累加器。最後,我們就有了一個完美的扁平化陣列。 我知道您也可以使用`Array.flat()`來做到這一點。然而,了解如何使用reduce 很重要,以防您想對每個專案執行額外的操作。 ### 用例 3:對物件進行分組 假設您有一個物件陣列,並且您希望根據特定屬性對它們進行分組。 reduce() 是完成這項工作的完美工具。 ``` interface Person { name: string; age: number; } const people: Person[] = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 25 }, { name: 'Dave', age: 30 } ]; const groupedByAge: { [key: number]: Person[] } = people.reduce((acc, curr) => { if (!acc[curr.age]) { acc[curr.age] = []; } acc[curr.age].push(curr); return acc; }, {}); console.log(groupedByAge); /* Output: { '25': [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 25 }], '30': [{ name: 'Bob', age: 30 }, { name: 'Dave', age: 30 }] } */ ``` 在本例中,我們使用一個物件作為初始累加器值。我們檢查累加器是否已經具有當前年齡的屬性。如果沒有,我們為該年齡建立一個空陣列。然後,我們將目前物件推入對應的年齡陣列中。最後,我們得到一個物件,其中鍵是年齡,值是該年齡的人的陣列。 現在您也可以使用更新的`groupBy`方法,但是,理解這個久經考驗的真正經典方法很重要。 ### 用例 4:建立查找圖 我個人最喜歡的是使用reduce()從陣列建立查找映射。在效能和程式碼可讀性方面,它改變了遊戲規則。停止使用那些緩慢的 find() 或 filter() 呼叫。 ``` interface Product { id: number; name: string; price: number; } const products: Product[] = [ { id: 1, name: 'Laptop', price: 999 }, { id: 2, name: 'Phone', price: 699 }, { id: 3, name: 'Tablet', price: 499 }, ]; const productMap: { [key: number]: Product } = products.reduce((acc, curr) => { acc[curr.id] = curr; return acc; }, {}); console.log(productMap); /* Output: { '1': { id: 1, name: 'Laptop', price: 999 }, '2': { id: 2, name: 'Phone', price: 699 }, '3': { id: 3, name: 'Tablet', price: 499 } } */ // Accessing a product by ID const laptop: Product = productMap[1]; console.log(laptop); // Output: { id: 1, name: 'Laptop', price: 999 } ``` 透過使用reduce()建立查找映射,您可以以恆定的時間複雜度透過元素的唯一辨識碼來存取元素。不再需要循環遍歷陣列來尋找特定專案。 ### 用例 5:計算出現次數 曾經需要計算陣列中元素的出現次數嗎? reduce() 已經幫你解決了。 ``` const fruits: string[] = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']; const fruitCounts: { [key: string]: number } = fruits.reduce((acc, curr) => { acc[curr] = (acc[curr] || 0) + 1; return acc; }, {}); console.log(fruitCounts); /* Output: { 'apple': 3, 'banana': 2, 'orange': 1 } */ ``` 在這個例子中,我們初始化一個空物件作為累加器。對於陣列中的每個水果,我們檢查它是否已作為累加器物件中的屬性存在。如果是,我們將其計數加 1;否則,我們將其初始化為 1。 ### 用例 6:組合函數 函數式程式設計愛好者一定會喜歡這個。 reduce() 是一個強大的函陣列合工具。您可以使用它來建立逐步轉換資料的函數管道。 ``` const add5 = (x: number): number => x + 5; const multiply3 = (x: number): number => x * 3; const subtract2 = (x: number): number => x - 2; const composedFunctions: ((x: number) => number)[] = [add5, multiply3, subtract2]; const result: number = composedFunctions.reduce((acc, curr) => curr(acc), 10); console.log(result); // Output: 43 ``` 在這個範例中,我們有一個函數陣列,我們希望將其按順序應用到初始值 10。最終結果是按組合順序應用所有函數的結果。 ### 用例 7:實作簡單的類似 Redux 的狀態管理 如果您使用過 Redux,您就會知道它在管理應用程式中的狀態方面有多強大。你猜怎麼了?你可以使用reduce()來實作一個簡單的類似Redux的狀態管理系統。 ``` interface State { count: number; todos: string[]; } interface Action { type: string; payload?: any; } const initialState: State = { count: 0, todos: [], }; const actions: Action[] = [ { type: 'INCREMENT_COUNT' }, { type: 'ADD_TODO', payload: 'Learn Array.reduce()' }, { type: 'INCREMENT_COUNT' }, { type: 'ADD_TODO', payload: 'Master TypeScript' }, ]; const reducer = (state: State, action: Action): State => { switch (action.type) { case 'INCREMENT_COUNT': return { ...state, count: state.count + 1 }; case 'ADD_TODO': return { ...state, todos: [...state.todos, action.payload] }; default: return state; } }; const finalState: State = actions.reduce(reducer, initialState); console.log(finalState); /* Output: { count: 2, todos: ['Learn Array.reduce()', 'Master TypeScript'] } */ ``` 在此範例中,我們有一個初始狀態物件和一組操作。我們定義一個reducer函數,它接受當前狀態和一個動作,並根據動作類型返回一個新狀態。透過使用reduce(),我們可以將每個動作依序應用於狀態,從而得到最終狀態。這就像擁有一個迷你 Redux。 ### 用例 8:產生唯一值 有時,您可能有一個包含重複值的陣列,並且您需要僅提取唯一的值。 reduce() 可以幫助您輕鬆實現這一點。 ``` const numbers: number[] = [1, 2, 3, 2, 4, 3, 5, 1, 6]; const uniqueNumbers: number[] = numbers.reduce((acc, curr) => { if (!acc.includes(curr)) { acc.push(curr); } return acc; }, []); console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5, 6] ``` 在這裡,我們初始化一個空陣列作為累加器。對於原始陣列中的每個數字,我們使用includes()方法檢查它是否已存在於累加器中。如果沒有,我們將其推入累加器陣列。最終結果是一個僅包含原始陣列中唯一值的陣列。 ### 用例 9:計算平均值 想要計算一組數字的平均值? reduce() 為您提供支援! ``` const grades: number[] = [85, 90, 92, 88, 95]; const average: number = grades.reduce((acc, curr, index, array) => { acc += curr; if (index === array.length - 1) { return acc / array.length; } return acc; }, 0); console.log(average); // Output: 90 ``` 在此範例中,我們將累加器初始化為 0。當我們到達最後一個元素時(使用索引和 array.length 檢查),我們將累加器除以成績總數來計算平均值。 性能考量🏎️ ------ 雖然 Array.reduce() 非常強大且用途廣泛,但了解潛在的效能缺陷非常重要,尤其是在處理大型陣列或複雜操作時。一個常見的陷阱是在每次reduce()迭代中建立新的物件或陣列,這可能會導致過多的記憶體分配並影響效能。 例如,考慮以下程式碼: ``` const numbers: number[] = [1, 2, 3, 4, 5]; const doubledNumbers: number[] = numbers.reduce((acc, curr) => { return [...acc, curr * 2]; }, []); console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10] ``` 在本例中,我們使用展開運算子 (...) 在每次迭代中建立一個新陣列,這可能會效率低下。相反,我們可以透過直接改變累加器陣列來優化程式碼: ``` const numbers: number[] = [1, 2, 3, 4, 5]; const doubledNumbers: number[] = numbers.reduce((acc, curr) => { acc.push(curr * 2); return acc; }, []); console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10] ``` 透過使用 push() 來改變累加器陣列,我們可以避免在每次迭代中建立新陣列,從而獲得更好的效能。 類似地,在處理物件時,直接改變累加器物件比使用擴充運算子建立新物件更有效: ``` const people: Person[] = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 25 }, { name: 'Dave', age: 30 } ]; const groupedByAge: { [key: number]: Person[] } = people.reduce((acc, curr) => { if (!acc[curr.age]) { acc[curr.age] = []; } acc[curr.age].push(curr); return acc; }, {}); ``` 透過直接改變累加器物件,我們優化了reduce()操作的效能。 然而,值得注意的是,在某些情況下,在每次迭代中建立新的物件或陣列可能是必要的或更具可讀性。根據您的具體用例和您正在使用的資料大小,在效能和程式碼清晰度之間取得平衡非常重要。 結論 -- 你有它。九個令人難以置信的用例展示了 Array.reduce() 的強大功能和多功能性。從將數字求和到展平陣列、對物件進行分組到建立查找映射、對出現次數進行計數到組合函數,甚至實現狀態管理和計算平均值, `Array.reduce()`被證明是js 工具包中的強大工具。 你怎麼認為?您最喜歡的陣列方法是什麼? 感謝您的閱讀,願 reduce() 的力量與您同在。 ✨🐐✨ --- 原文出處:https://dev.to/mattlewandowski93/arrayreduce-is-goated-1f1j

掌握 SQL:結構化查詢語言綜合指南

介紹 -- 在上一篇部落格文章中,我們共同探討了以下內容的綜合指南: {% 嵌入 https://dev.to/louaiboumediene/mastering-relational-database-design-a-compressive-guide-3jh8 %} 在本文中,我們將在較高層次上發現實際用於實現資料庫模式設計的語言的語法和核心功能... SQL。 那麼...讓我們深入探討吧! ![讓我們深入了解圖像](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cvmr1vh4frdyjfmzf5sh.gif) --- 什麼是 SQL ------- SQL,即結構化查詢語言,是用於與所有**RDMS**對話的外觀語言,但是大多數時候,作為後端工程師(我們不是資料庫工程師),我們不直接使用 SQL,而是使用物件關係映射器**ORM**它在原始SQL 之上提供了一個更好、更可靠的接口,以便用我們首選的程式語言與資料庫進行通信,但是我們仍然需要SQL 的基本知識,以便快速、簡單地操作以及與資料庫互動。 ![如果我告訴你表情包怎麼辦](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fvpr0nujx4fed7e4xvh3.png) --- 基本 SQL 查詢 --------- 基本 SQL 查詢涉及使用 SELECT、DISTINCT、WHERE、LIMIT 和 OFFSET 等命令從資料庫表中選擇特定資料。 ``` -- Selecting all columns from a table SELECT * FROM employees; -- Selecting specific columns SELECT first_name, last_name FROM employees; -- Using DISTINCT to get unique values SELECT DISTINCT department_id FROM employees; -- Using WHERE to filter results SELECT * FROM employees WHERE department_id = 10; -- Using LIMIT to limit the number of results SELECT * FROM employees LIMIT 5; -- Using OFFSET to skip certain rows SELECT * FROM employees OFFSET 5; ``` --- 過濾資料 ---- 在 SQL 中篩選資料可讓您根據某些條件從表格中擷取特定記錄,例如使用 &gt;、&lt;、= 等比較運算子以及 AND、OR 和 NOT 等邏輯運算子。 ``` -- Using comparison operators SELECT * FROM employees WHERE salary > 50000; -- Using logical operators SELECT * FROM employees WHERE department_id = 10 AND salary > 50000; -- Using IN and NOT IN SELECT * FROM employees WHERE department_id IN (10, 20); -- Using BETWEEN SELECT * FROM employees WHERE salary BETWEEN 40000 AND 60000; -- Using LIKE for pattern matching SELECT * FROM employees WHERE last_name LIKE 'S%'; ``` --- 資料排序 ---- SQL 中的資料排序是使用 ORDER BY 子句根據指定列以升序或降序排列檢索到的記錄。 ``` -- Sorting data in ascending order SELECT * FROM employees ORDER BY salary; -- Sorting data in descending order SELECT * FROM employees ORDER BY salary DESC; -- Sorting by multiple columns SELECT * FROM employees ORDER BY department_id, salary DESC; ``` --- 聚合函數 ---- SQL 中的聚合函數對一組值執行計算並傳回單一值。常見的聚合函數包括 COUNT、SUM、AVG、MIN 和 MAX。 ``` -- Counting the number of rows SELECT COUNT(*) FROM employees; -- Calculating total salary SELECT SUM(salary) FROM employees; -- Finding average salary SELECT AVG(salary) FROM employees; -- Finding minimum salary SELECT MIN(salary) FROM employees; -- Finding maximum salary SELECT MAX(salary) FROM employees; ``` --- 資料分組 ---- 在 SQL 中將資料分組可讓您使用 GROUP BY 子句(通常與聚合函數結合使用)對指定列中具有相同值的行進行分組。 ``` -- Grouping data by department SELECT department_id, COUNT(*) FROM employees GROUP BY department_id; -- Using HAVING to filter grouped data SELECT department_id, COUNT(*) FROM employees GROUP BY department_id HAVING COUNT(*) > 5; ``` --- 加入 -- SQL 中的聯結會根據相關資料列組合來自多個資料表的資料,以擷取跨這些資料表的資料。 ``` -- Inner Join SELECT * FROM employees INNER JOIN departments ON employees.department_id = departments.department_id; -- Left Join SELECT * FROM employees LEFT JOIN departments ON employees.department_id = departments.department_id; -- Right Join SELECT * FROM employees RIGHT JOIN departments ON employees.department_id = departments.department_id; -- Full Outer Join SELECT * FROM employees FULL OUTER JOIN departments ON employees.department_id = departments.department_id; ``` --- 子查詢 --- SQL 中的子查詢是另一個查詢中的巢狀查詢,用於檢索依賴另一個查詢結果的資料。 ``` -- Subquery example SELECT * FROM employees WHERE department_id IN (SELECT department_id FROM departments WHERE location_id = 1700); -- Correlated subquery example SELECT * FROM employees e WHERE salary > (SELECT AVG(salary) FROM employees WHERE department_id = e.department_id); ``` --- 意見 -- SQL 中的檢視是根據查詢結果產生的虛擬表,提供了一種簡化複雜查詢並限制對某些資料的存取的方法。 ``` -- Creating a view CREATE VIEW high_paid_employees AS SELECT * FROM employees WHERE salary > 80000; -- Updating a view CREATE OR REPLACE VIEW high_paid_employees AS SELECT * FROM employees WHERE salary > 90000; -- Dropping a view DROP VIEW IF EXISTS high_paid_employees; ``` --- 索引 -- SQL 中的索引透過在列上建立索引來提高查詢效能,從而實現更快的資料檢索。 ``` -- Creating an index CREATE INDEX idx_lastname ON employees(last_name); -- Dropping an index DROP INDEX idx_lastname; ``` --- 交易 -- SQL 中的交易透過將 SQL 語句分組為原子單元來確保資料完整性,從而確保所有語句都成功執行或全部都不執行。 ``` -- Beginning a transaction BEGIN TRANSACTION; -- Committing a transaction COMMIT; -- Rolling back a transaction ROLLBACK; ``` --- 儲存過程 ---- SQL中的預存程序是儲存在資料庫中的預編譯的SQL程式碼,可以透過單一命令執行,通常用於封裝頻繁執行的任務 ``` -- Creating a stored procedure CREATE PROCEDURE get_employee (IN employee_id INT) BEGIN SELECT * FROM employees WHERE employee_id = employee_id; END; -- Executing a stored procedure CALL get_employee(100); -- Modifying a stored procedure ALTER PROCEDURE get_employee (IN employee_id INT) BEGIN SELECT employee_id, first_name, last_name FROM employees WHERE employee_id = employee_id; END; -- Dropping a stored procedure DROP PROCEDURE IF EXISTS get_employee; ``` --- 備份與復原 ----- SQL 中的備份和復原涉及建立資料庫備份以防止資料遺失,並在資料庫發生故障或損壞時還原它們。 ``` -- Creating a full backup BACKUP DATABASE dbname TO disk = 'path_to_backup'; -- Creating a differential backup BACKUP DATABASE dbname TO disk = 'path_to_backup' WITH DIFFERENTIAL; -- Creating a transaction log backup BACKUP LOG dbname TO disk = 'path_to_backup'; -- Restoring from a backup RESTORE DATABASE dbname FROM disk = 'path_to_backup'; ``` --- SQL 方言和特定於供應商的擴展 ---------------- 雖然 SQL 是一種標準化語言,但不同的資料庫供應商已經實作了自己的擴充和方言,導致不同 RDBMS 之間 SQL 的編寫和執行方式略有不同。這些變更可能會影響使用特定資料庫系統的開發人員可用的語法、函數和特性。 例如,以下是特定於供應商的 SQL 方言和擴展的一些範例: **甲骨文SQL** : - Oracle SQL 包括專有擴展,例如分層查詢、分析函數和用於資料建模的 MODEL 子句。 - 範例: `SELECT CUBE(product, region) FROM sales;` (CUBE 是 Oracle 特定的用於產生小計的擴充) **SQL Server(微軟)** : - SQL Server 包含 T-SQL (Transact-SQL),它透過串流控制語言建構、錯誤處理和流程程式設計建構等功能擴展了標準 SQL。 - 範例: `SELECT ISNULL(column_name, 'default_value') FROM table_name;` (ISNULL 是一個 T-SQL 函數) **MySQL** : - MySQL 包括空間資料類型和函數、視窗函數以及用於正規表示式匹配的 REGEX 運算子等擴充。 - 範例: `SELECT column_name REGEXP '^pattern' FROM table_name;` (REGEXP 是 MySQL 特定的運算子) **PostgreSQL** : - PostgreSQL 包括陣列、JSON 支援、全文搜尋和範圍資料類型等擴充。 - 範例: `SELECT column_name || 'suffix' FROM table_name;` (|| 是 PostgreSQL 特定的字串連接運算子) ![RDBMS 之間的差異](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z7m0q9jdx3opw29zja6j.png) 所以最合乎邏輯的方法是: 1. **基礎知識**:了解關聯式資料庫設計的基礎:實體、鍵、關係…。 。 2. **SQL** :學習 SQL 作為獨立語言的基礎知識。 3. **選擇 RDBM** :選擇最適合您的 RDBMS,然後按照其所有特殊語法和結構來使用它。 結論 -- SQL 本身就是一個廣闊的領域,包含許多我們沒有涉及的概念。事務、備份和文件管理只是更廣泛範圍的幾個範例。然而,對於像我們這樣的後端工程師來說,我們所介紹的基礎知識足以作為 SQL 的基礎概述。 --- 原文出處:https://dev.to/louaiboumediene/mastering-sql-comprehensive-guide-to-structured-query-language-4gh

5 分鐘了解記憶化

記憶化是另一個令人生畏的術語,當你理解它時,它就會變得非常直觀。今天我們就來了解什麼是記憶吧! --- ### 一些筆記 - 我製作了本教學的影片版本![在這裡](https://www.youtube.com/watch?v=6tbUPqnu-Ws)查看一下。 - 如果您喜歡這篇文章,請考慮訂閱我的免費每週[網頁開發電子報](https://buttondown.email/devtuts)! --- 介紹 == 記憶化是許多程式語言中使用的最佳化技術,用於減少冗餘、昂貴的函數呼叫的數量。這是透過根據函數的輸入快取函數的返回值來完成的。在這篇文章中,我們將建立一個次優但希望具有教育意義的 JavaScript 函數記憶體! 首先,需要記憶的昂貴函數 ============ 這是一個供我們記憶的函數。它以非常低效的方式求出數字的平方。 ``` const inefficientSquare = num => { let total = 0; for (let i = 0; i < num; i++) { for (let j = 0; j < num; j++) { total++; } } return total; }; ``` 我們可以使用相同的值來執行這個函數,並且每次都需要一段時間來執行。 ``` const start = new Date(); inefficientSquare(40000); console.log(new Date() - start); // 1278 const start2 = new Date(); inefficientSquare(40000); console.log(new Date() - start2); // 1245 ``` 每次都超過一秒,哎呀! 為我們的 Memoizer 編寫偽程式碼 =================== 在編寫任何程式碼之前,讓我們先透過記憶體進行推理。 - 將對函數的引用作為輸入 - 傳回一個函數(因此可以像平常一樣使用) - 建立某種緩存來保存先前函數呼叫的結果 - 以後任何時候呼叫該函數,都會傳回快取結果(如果存在) - 如果快取的值不存在,則呼叫該函數並將結果儲存在快取中 真實程式碼時間 ====== 這是上述偽程式碼大綱的實作。正如簡介中提到的,這是次優的,您**不應該在生產中使用它**。後面我會解釋為什麼! ``` // Takes a reference to a function const memoize = func => { // Creates a cache of results const results = {}; // Returns a function return (...args) => { // Create a key for results cache const argsKey = JSON.stringify(args); // Only execute func if no cached value if (!results[argsKey]) { // Store function call result in cache results[argsKey] = func(...args); } // Return cached value return results[argsKey]; }; }; ``` 此實作中最次優的部分,以及為什麼我不建議在生產程式碼中使用它,是使用`JSON.stringify`在`results`快取中建立鍵。 `JSON.stringify`的最大問題是它不會序列化某些輸入,例如函數和符號(以及您在 JSON 中找不到的任何內容)。 在昂貴的功能上測試我們的記憶體 =============== 讓我們複製`inefficientSquare`範例,但這次我們將使用 memoizer 來快取結果。 ``` const memoize = func => { const results = {}; return (...args) => { const argsKey = JSON.stringify(args); if (!results[argsKey]) { results[argsKey] = func(...args); } return results[argsKey]; }; }; const inefficientSquare = memoize(num => { let total = 0; for (let i = 0; i < num; i++) { for (let j = 0; j < num; j++) { total++; } } return total; }); const start = new Date(); inefficientSquare(40000); console.log(new Date() - start); // 1251 const start2 = new Date(); inefficientSquare(40000); console.log(new Date() - start2); // 0 ``` 成功!第二次我們使用相同的輸入呼叫`inefficientSquare`時,不需要時間重新計算;我們只是從物件中提取快取的值。 只記住純函數! ======= 記憶化很棒,但只有當你的函數是純函數時才有效。換句話說,如果函數的回傳值不僅僅依賴其輸入,那麼這些輸入的快取值將不會總是正確的。此外,如果您的函數有副作用,記憶體不會複製這些副作用,它只會傳回最終返回的函數值。 結論 == 現在您應該很清楚我們如何以及為什麼使用記憶化!雖然我們的記憶功能不是最佳的,但您可以使用許多第三方函式庫,它們會做得更好。只要確保您記住的函數是純函數即可! --- 原文出處:https://dev.to/nas5w/an-introduction-to-memoization-59o

AI 驅動的前端 UI 元件產生器(Next.js、GPT4、Langchain 和 CopilotKit)

**長話短說** -------- 在本文中,您將了解如何建立由 AI 驅動的前端 UI 元件產生器,該產生器使您能夠透過實作教學產生 Next.js Tailwind CSS UI 元件。 我們將介紹如何: - 使用 Next.js、TypeScript 和 Tailwind CSS 建立 UI 元件產生器 Web 應用程式。 - 使用 CopilotKit 將 AI 功能整合到 UI 元件產生器中。 - 整合嵌入式程式碼編輯器以變更產生的程式碼。 先決條件 ---- 要完全理解本教程,您需要對 React 或 Next.js 有基本的了解。 以下是建立 AI 支援的 UI 元件產生器所需的工具: - [Ace 程式碼編輯器](https://ace.c9.io/)- 用 JvaScript 編寫的嵌入式程式碼編輯器,與本機編輯器的功能和效能相符。 - [Langchain](https://www.langchain.com/) - 提供了一個框架,使人工智慧代理能夠搜尋網路並研究任何主題。 - [OpenAI API](https://platform.openai.com/api-keys) - 提供 API 金鑰,讓您能夠使用 ChatGPT 模型執行各種任務。 - [Tavily AI](https://tavily.com/) - 一個搜尋引擎,使人工智慧代理能夠在應用程式中進行研究並存取即時知識。 - [CopilotKit](https://github.com/CopilotKit) - 一個開源副駕駛框架,用於建立自訂 AI 聊天機器人、應用程式內 AI 代理程式和文字區域。 專案設定和套件安裝 --------- 首先,透過在終端機中執行以下程式碼片段來建立 Next.js 應用程式: ``` npx create-next-app@latest aiuigenerator ``` 選擇您首選的配置設定。在本教學中,我們將使用 TypeScript 和 Next.js App Router。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0c2uq47mrd3ppxqvr1v7.png) 接下來,安裝 Ace 程式碼編輯器和 Langchain 軟體套件及其相依性。 ``` npm install react-ace @langchain/langgraph ``` 最後,安裝 CopilotKit 軟體套件。這些套件使我們能夠從 React 狀態檢索資料並將 AI copilot 新增至應用程式。 ``` npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend ``` 恭喜!您現在已準備好建立由人工智慧驅動的部落格。 **建構 UI 元件產生器前端** ----------------- 在本節中,我將引導您完成使用靜態內容建立 UI 元件產生器前端的過程,以定義生成器的使用者介面。 首先,請在程式碼編輯器中前往`/[root]/src/app`並建立一個名為`components`的資料夾。在 Components 資料夾中,建立兩個名為`Header.tsx`和`CodeTutorial.tsx`的檔案。 在`Header.tsx`檔案中,新增以下程式碼,定義一個名為`Header`的功能元件,該元件將呈現生成器的導覽列。 ``` "use client"; import Link from "next/link"; export default function Header() { return ( <> <header className="flex flex-wrap sm:justify-start sm:flex-nowrap z-50 w-full bg-gray-800 border-b border-gray-200 text-sm py-3 sm:py-0 "> <nav className="relative max-w-7xl w-full mx-auto px-4 sm:flex sm:items-center sm:justify-between sm:px-6 lg:px-8" aria-label="Global"> <div className="flex items-center justify-between"> <Link className="w-full flex-none text-xl text-white font-semibold p-6" href="/" aria-label="Brand"> AI-UI-Components-Generator </Link> </div> </nav> </header> </> ); } ``` 在`CodeTutorial.tsx`檔案中,加入以下程式碼,定義一個名為`CodeTutorial`的功能元件,該元件呈現 UI 元件產生器主頁,該首頁將顯示產生的 UI 元件、嵌入式程式碼編輯器和產生的實作教學。 ``` "use client"; import Markdown from "react-markdown"; import { useState } from "react"; import AceEditor from "react-ace"; import React from "react"; export default function CodeTutorial() { const [code, setCode] = useState<string[]>([ `<h1 class="text-red-500">Hello World</h1>`, ]); const [codeToDisplay, setCodeToDisplay] = useState<string>(code[0] || ""); const [codeTutorial, setCodeTutorial] = useState(``); function onChange(newCode: any) { setCodeToDisplay(newCode); } return ( <> <main className=" min-h-screen px-4"> <div className="w-full h-full min-h-[70vh] flex justify-between gap-x-1 "> <div className="w-2/3 min-h-[60vh] rounded-lg bg-white shadow-lg p-2 border mt-8 overflow-auto"> <div className="w-full min-h-[60vh] rounded-lg" dangerouslySetInnerHTML={{ __html: codeToDisplay }} /> </div> <AceEditor placeholder="Placeholder Text" mode="html" theme="monokai" name="blah2" className="w-[50%] min-h-[60vh] p-2 mt-8 rounded-lg" onChange={onChange} fontSize={14} lineHeight={19} showPrintMargin={true} showGutter={true} highlightActiveLine={true} value={codeToDisplay} setOptions={{ enableBasicAutocompletion: true, enableLiveAutocompletion: true, enableSnippets: false, showLineNumbers: true, tabSize: 2, }} /> </div> <div className="w-10/12 mx-auto"> <div className="mt-8"> <h1 className="text-white text-center text-xl font-semibold p-6"> Code Tutorial </h1> {codeTutorial ? ( <Markdown className="text-white">{codeTutorial}</Markdown> ) : ( <div className="text-white"> The Code Tutorial Will Appear Here </div> )} </div> </div> </main> </> ); } ``` 接下來,前往`/[root]/src/page.tsx`文件,新增以下程式碼,導入`CodeTutorial`和`Header`元件,並定義名為`Home`的功能元件。 ``` import React from "react"; import Header from "./components/Header"; import CodeTutorial from "./components/CodeTutorial"; export default function Home() { return ( <> <Header /> <CodeTutorial /> </> ); } ``` 接下來,刪除 globals.css 檔案中的 CSS 程式碼並新增以下 CSS 程式碼。 ``` @tailwind base; @tailwind components; @tailwind utilities; @tailwind base; @tailwind components; @tailwind utilities; body { height: 100vh; background-color: rgb(16, 23, 42); } pre { margin: 1rem; padding: 1rem; border-radius: 10px; background-color: black; overflow: auto; } h2, p { padding-bottom: 1rem; padding-top: 1rem; } code { margin-bottom: 2rem; } ``` 最後,在命令列上執行命令`npm run dev` ,然後導航到 http://localhost:3000/。 現在您應該在瀏覽器上查看 UI 元件產生器前端,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/id9z3bizkb2bghbe4bxb.png) **使用 CopilotKit 將 AI 功能整合到元件產生器** --------------------------------- 在本節中,您將學習如何為 UI 元件產生器新增 AI 副駕駛以產生 UI 元件程式碼以及使用 CopilotKit 的實作教學。 CopilotKit 提供前端和[後端](https://docs.copilotkit.ai/getting-started/quickstart-backend)套件。它們使您能夠插入 React 狀態並使用 AI 代理在後端處理應用程式資料。 首先,讓我們將 CopilotKit React 元件加入到部落格前端。 ### **將 CopilotKit 新增至部落格前端** 在這裡,我將引導您完成將 UI 元件產生器與 CopilotKit 前端整合的過程,以方便產生 UI 元件程式碼和實作教學。 首先,使用下面的程式碼片段導入`/[root]/src/app/components/CodeTutorial.tsx`檔案頂部的自訂掛鉤`useMakeCopilotReadable`和`useCopilotAction` 。 ``` import { useCopilotAction, useMakeCopilotReadable, } from "@copilotkit/react-core"; ``` 在`CodeTutorial`函數內的狀態變數下方,加入以下程式碼,該程式碼使用`useMakeCopilotReadable`掛鉤來新增將作為應用程式內聊天機器人的上下文產生的程式碼。該鉤子使副駕駛可以讀取程式碼。 ``` useMakeCopilotReadable(codeToDisplay); ``` 在上面的程式碼下方,新增以下程式碼,該程式碼使用`useCopilotAction`掛鉤來設定名為`generateCodeAndImplementationTutorial`的操作,該操作將啟用 UI 元件程式碼和實作教學課程的產生。 這個操作接受兩個參數,稱為`code`和`tutorial` ,這兩個參數可以產生 UI 元件程式碼和實作教程。 該操作包含一個處理函數,該函數根據給定的提示產生 UI 元件程式碼和實作教程。 在處理函數內部, `codeToDisplay`狀態會使用新產生的程式碼進行更新,而`codeTutorial`狀態會使用新產生的教學課程進行更新,如下所示。 ``` useCopilotAction( { name: "generateCodeAndImplementationTutorial", description: "Create Code Snippet with React.js(Next.js), tailwindcss and an implementation tutorial of the code generated.", parameters: [ { name: "code", type: "string", description: "Code to be generated", required: true, }, { name: "tutorial", type: "string", description: "Markdown of step by step guide tutorial on how to use the generated code accompanied with the code. Include introduction, prerequisites and what happens at every step accompanied with code generated earlier. Don't forget to add how to render the code on browser.", required: true, }, ], handler: async ({ code, tutorial }) => { setCode((prev) => [...prev, code]); setCodeToDisplay(code); setCodeTutorial(tutorial); }, }, [codeToDisplay, codeTutorial] ); ``` 之後,請前往`/[root]/src/app/page.tsx`檔案並使用下面的程式碼匯入頂部的 CopilotKit 前端套件和樣式。 ``` import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import "@copilotkit/react-ui/styles.css"; ``` 然後使用`CopilotKit`包裝`CopilotSidebar`和`CodeTutorial`元件,如下所示。 `CopilotKit`元件指定 CopilotKit 後端端點 ( `/api/copilotkit/` ) 的 URL,而`CopilotSidebar`呈現應用程式內聊天機器人,您可以提示產生 UI 元件程式碼和實作教學。 ``` export default function Home() { return ( <> <Header /> <CopilotKit url="/api/copilotkit"> <CopilotSidebar instructions="Help the user generate code. Ask the user if to generate its tutorial." defaultOpen={true} labels={{ title: "Code & Tutorial Generator", initial: "Hi! 👋 I can help you generate code and its tutorial.", }}> <CodeTutorial /> </CopilotSidebar> </CopilotKit> </> ); } ``` 之後,執行開發伺服器並導航到 http://localhost:3000。您應該會看到應用程式內聊天機器人已整合到 UI 元件產生器中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ty4g6tuluhfiqtnnyxvg.png) ### **將 CopilotKit 後端加入博客** 在這裡,我將引導您完成將 UI 元件產生器與 CopilotKit 後端整合的過程,該後端處理來自前端的請求,並提供函數呼叫和各種 LLM 後端(例如 GPT)。 此外,我們將整合一個名為 Tavily 的人工智慧代理,它可以研究網路上的任何主題。 首先,在根目錄中建立一個名為`.env.local`的檔案。然後在保存`ChatGPT`和`Tavily` Search API 金鑰的檔案中加入下面的環境變數。 ``` OPENAI_API_KEY="Your ChatGPT API key" TAVILY_API_KEY="Your Tavily Search API key" ``` 若要取得 ChatGPT API 金鑰,請導覽至 https://platform.openai.com/api-keys。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mjl2g88iedd1n0qkd3ai.png) 若要取得 Tavilly Search API 金鑰,請導覽至 https://app.tavily.com/home ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m00kyux6biskw7xn2wec.png) 之後,轉到`/[root]/src/app`並建立一個名為`api`的資料夾。在`api`資料夾中,建立一個名為`copilotkit`的資料夾。 在`copilotkit`資料夾中,建立一個名為`research.ts`的檔案。然後導航到[該 Research.ts gist 文件](https://gist.github.com/TheGreatBonnie/58dc21ebbeeb8cbb08df665db762738c),複製程式碼,並將其新增至**`research.ts`**檔案中 接下來,在`/[root]/src/app/api/copilotkit`資料夾中建立一個名為`route.ts`的檔案。該文件將包含設定後端功能來處理 POST 請求的程式碼。它有條件地包括對給定主題進行研究的“研究”操作。 現在在文件頂部導入以下模組。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; // For backend functionality with CopilotKit. import { researchWithLangGraph } from "./research"; // Import a custom function for conducting research. import { AnnotatedFunction } from "@copilotkit/shared"; // For annotating functions with metadata. ``` 在上面的程式碼下面,定義一個執行時間環境變數和一個名為`researchAction`的函數,該函數使用下面的程式碼研究某個主題。 ``` // Define a runtime environment variable, indicating the environment where the code is expected to run. export const runtime = "edge"; // Define an annotated function for research. This object includes metadata and an implementation for the function. const researchAction: AnnotatedFunction<any> = { name: "research", // Function name. description: "Call this function to conduct research on a certain topic. Respect other notes about when to call this function", // Function description. argumentAnnotations: [ // Annotations for arguments that the function accepts. { name: "topic", // Argument name. type: "string", // Argument type. description: "The topic to research. 5 characters or longer.", // Argument description. required: true, // Indicates that the argument is required. }, ], implementation: async (topic) => { // The actual function implementation. console.log("Researching topic: ", topic); // Log the research topic. return await researchWithLangGraph(topic); // Call the research function and return its result. }, }; ``` 然後在上面的程式碼下加入下面的程式碼來定義處理POST請求的非同步函數。 ``` // Define an asynchronous function that handles POST requests. export async function POST(req: Request): Promise<Response> { const actions: AnnotatedFunction<any>[] = []; // Initialize an array to hold actions. // Check if a specific environment variable is set, indicating access to certain functionality. if (process.env.TAVILY_API_KEY) { actions.push(researchAction); // Add the research action to the actions array if the condition is true. } // Instantiate CopilotBackend with the actions defined above. const copilotKit = new CopilotBackend({ actions: actions, }); // Use the CopilotBackend instance to generate a response for the incoming request using an OpenAIAdapter. return copilotKit.response(req, new OpenAIAdapter()); } ``` 如何產生 UI 元件 ---------- 現在轉到您之前整合的應用程式內聊天機器人,並給它一個提示,例如「產生聯絡表單」。 生成完成後,您應該會看到生成的聯絡表單元件及其實作教程,如下所示。您也可以使用嵌入式程式碼編輯器修改產生的程式碼。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/43t9oauptomio4cy1gwr.png) ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/297vxxiqti56ydevfmyl.png) 恭喜!您已完成本教學的專案。 結論 -- [CopilotKit](https://copilotkit.ai/)是一款令人難以置信的工具,可讓您在幾分鐘內將 AI Copilot 加入到您的產品中。無論您是對人工智慧聊天機器人和助理感興趣,還是對複雜任務的自動化感興趣,CopilotKit 都能讓您輕鬆實現。 如果您需要建立 AI 產品或將 AI 工具整合到您的軟體應用程式中,您應該考慮 CopilotKit。 您可以在 GitHub 上找到本教學的源程式碼: <https://github.com/TheGreatBonnie/AIPoweredUIComponentsGenerator> --- 原文出處:https://dev.to/tcms/ai-powered-frontend-ui-components-generator-nextjs-gpt4-langchain-copilotkit-1hac

AI 驅動的前端 UI 元件產生器(Next.js、GPT4、Langchain 和 CopilotKit)

**長話短說** -------- 在本文中,您將了解如何建立由 AI 驅動的前端 UI 元件產生器,該產生器使您能夠透過實作教學產生 Next.js Tailwind CSS UI 元件。 我們將介紹如何: - 使用 Next.js、TypeScript 和 Tailwind CSS 建立 UI 元件產生器 Web 應用程式。 - 使用 CopilotKit 將 AI 功能整合到 UI 元件產生器中。 - 整合嵌入式程式碼編輯器以變更產生的程式碼。 先決條件 ---- 要完全理解本教程,您需要對 React 或 Next.js 有基本的了解。 以下是建立 AI 支援的 UI 元件產生器所需的工具: - [Ace 程式碼編輯器](https://ace.c9.io/)- 用 JvaScript 編寫的嵌入式程式碼編輯器,與本機編輯器的功能和效能相符。 - [Langchain](https://www.langchain.com/) - 提供了一個框架,使人工智慧代理能夠搜尋網路並研究任何主題。 - [OpenAI API](https://platform.openai.com/api-keys) - 提供 API 金鑰,讓您能夠使用 ChatGPT 模型執行各種任務。 - [Tavily AI](https://tavily.com/) - 一個搜尋引擎,使人工智慧代理能夠在應用程式中進行研究並存取即時知識。 - [CopilotKit](https://github.com/CopilotKit) - 一個開源副駕駛框架,用於建立自訂 AI 聊天機器人、應用程式內 AI 代理程式和文字區域。 專案設定和套件安裝 --------- 首先,透過在終端機中執行以下程式碼片段來建立 Next.js 應用程式: ``` npx create-next-app@latest aiuigenerator ``` 選擇您首選的配置設定。在本教學中,我們將使用 TypeScript 和 Next.js App Router。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0c2uq47mrd3ppxqvr1v7.png) 接下來,安裝 Ace 程式碼編輯器和 Langchain 軟體套件及其相依性。 ``` npm install react-ace @langchain/langgraph ``` 最後,安裝 CopilotKit 軟體套件。這些套件使我們能夠從 React 狀態檢索資料並將 AI copilot 新增至應用程式。 ``` npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend ``` 恭喜!您現在已準備好建立由人工智慧驅動的部落格。 **建構 UI 元件產生器前端** ----------------- 在本節中,我將引導您完成使用靜態內容建立 UI 元件產生器前端的過程,以定義生成器的使用者介面。 首先,請在程式碼編輯器中前往`/[root]/src/app`並建立一個名為`components`的資料夾。在 Components 資料夾中,建立兩個名為`Header.tsx`和`CodeTutorial.tsx`的檔案。 在`Header.tsx`檔案中,新增以下程式碼,定義一個名為`Header`的功能元件,該元件將呈現生成器的導覽列。 ``` "use client"; import Link from "next/link"; export default function Header() { return ( <> <header className="flex flex-wrap sm:justify-start sm:flex-nowrap z-50 w-full bg-gray-800 border-b border-gray-200 text-sm py-3 sm:py-0 "> <nav className="relative max-w-7xl w-full mx-auto px-4 sm:flex sm:items-center sm:justify-between sm:px-6 lg:px-8" aria-label="Global"> <div className="flex items-center justify-between"> <Link className="w-full flex-none text-xl text-white font-semibold p-6" href="/" aria-label="Brand"> AI-UI-Components-Generator </Link> </div> </nav> </header> </> ); } ``` 在`CodeTutorial.tsx`檔案中,加入以下程式碼,定義一個名為`CodeTutorial`的功能元件,該元件呈現 UI 元件產生器主頁,該首頁將顯示產生的 UI 元件、嵌入式程式碼編輯器和產生的實作教學。 ``` "use client"; import Markdown from "react-markdown"; import { useState } from "react"; import AceEditor from "react-ace"; import React from "react"; export default function CodeTutorial() { const [code, setCode] = useState<string[]>([ `<h1 class="text-red-500">Hello World</h1>`, ]); const [codeToDisplay, setCodeToDisplay] = useState<string>(code[0] || ""); const [codeTutorial, setCodeTutorial] = useState(``); function onChange(newCode: any) { setCodeToDisplay(newCode); } return ( <> <main className=" min-h-screen px-4"> <div className="w-full h-full min-h-[70vh] flex justify-between gap-x-1 "> <div className="w-2/3 min-h-[60vh] rounded-lg bg-white shadow-lg p-2 border mt-8 overflow-auto"> <div className="w-full min-h-[60vh] rounded-lg" dangerouslySetInnerHTML={{ __html: codeToDisplay }} /> </div> <AceEditor placeholder="Placeholder Text" mode="html" theme="monokai" name="blah2" className="w-[50%] min-h-[60vh] p-2 mt-8 rounded-lg" onChange={onChange} fontSize={14} lineHeight={19} showPrintMargin={true} showGutter={true} highlightActiveLine={true} value={codeToDisplay} setOptions={{ enableBasicAutocompletion: true, enableLiveAutocompletion: true, enableSnippets: false, showLineNumbers: true, tabSize: 2, }} /> </div> <div className="w-10/12 mx-auto"> <div className="mt-8"> <h1 className="text-white text-center text-xl font-semibold p-6"> Code Tutorial </h1> {codeTutorial ? ( <Markdown className="text-white">{codeTutorial}</Markdown> ) : ( <div className="text-white"> The Code Tutorial Will Appear Here </div> )} </div> </div> </main> </> ); } ``` 接下來,前往`/[root]/src/page.tsx`文件,新增以下程式碼,導入`CodeTutorial`和`Header`元件,並定義名為`Home`的功能元件。 ``` import React from "react"; import Header from "./components/Header"; import CodeTutorial from "./components/CodeTutorial"; export default function Home() { return ( <> <Header /> <CodeTutorial /> </> ); } ``` 接下來,刪除 globals.css 檔案中的 CSS 程式碼並新增以下 CSS 程式碼。 ``` @tailwind base; @tailwind components; @tailwind utilities; @tailwind base; @tailwind components; @tailwind utilities; body { height: 100vh; background-color: rgb(16, 23, 42); } pre { margin: 1rem; padding: 1rem; border-radius: 10px; background-color: black; overflow: auto; } h2, p { padding-bottom: 1rem; padding-top: 1rem; } code { margin-bottom: 2rem; } ``` 最後,在命令列上執行命令`npm run dev` ,然後導航到 http://localhost:3000/。 現在您應該在瀏覽器上查看 UI 元件產生器前端,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/id9z3bizkb2bghbe4bxb.png) **使用 CopilotKit 將 AI 功能整合到元件產生器** --------------------------------- 在本節中,您將學習如何為 UI 元件產生器新增 AI 副駕駛以產生 UI 元件程式碼以及使用 CopilotKit 的實作教學。 CopilotKit 提供前端和[後端](https://docs.copilotkit.ai/getting-started/quickstart-backend)套件。它們使您能夠插入 React 狀態並使用 AI 代理在後端處理應用程式資料。 首先,我們將 CopilotKit React 元件加入到部落格前端。 ### **將 CopilotKit 新增至部落格前端** 在這裡,我將引導您完成將 UI 元件產生器與 CopilotKit 前端整合的過程,以方便產生 UI 元件程式碼和實作教學。 首先,使用下面的程式碼片段導入`/[root]/src/app/components/CodeTutorial.tsx`檔案頂部的自訂掛鉤`useMakeCopilotReadable`和`useCopilotAction` 。 ``` import { useCopilotAction, useMakeCopilotReadable, } from "@copilotkit/react-core"; ``` 在`CodeTutorial`函數內的狀態變數下方,加入以下程式碼,該程式碼使用`useMakeCopilotReadable`掛鉤來新增將作為應用程式內聊天機器人的上下文產生的程式碼。該鉤子使副駕駛可以讀取程式碼。 ``` useMakeCopilotReadable(codeToDisplay); ``` 在上面的程式碼下方,新增以下程式碼,該程式碼使用`useCopilotAction`掛鉤來設定名為`generateCodeAndImplementationTutorial`的操作,該操作將啟用 UI 元件程式碼和實作教學課程的產生。 這個操作接受兩個參數,稱為`code`和`tutorial` ,這兩個參數可以產生 UI 元件程式碼和實作教程。 該操作包含一個處理函數,該函數根據給定的提示產生 UI 元件程式碼和實作教程。 在處理函數內部, `codeToDisplay`狀態會使用新產生的程式碼進行更新,而`codeTutorial`狀態會使用新產生的教學課程進行更新,如下所示。 ``` useCopilotAction( { name: "generateCodeAndImplementationTutorial", description: "Create Code Snippet with React.js(Next.js), tailwindcss and an implementation tutorial of the code generated.", parameters: [ { name: "code", type: "string", description: "Code to be generated", required: true, }, { name: "tutorial", type: "string", description: "Markdown of step by step guide tutorial on how to use the generated code accompanied with the code. Include introduction, prerequisites and what happens at every step accompanied with code generated earlier. Don't forget to add how to render the code on browser.", required: true, }, ], handler: async ({ code, tutorial }) => { setCode((prev) => [...prev, code]); setCodeToDisplay(code); setCodeTutorial(tutorial); }, }, [codeToDisplay, codeTutorial] ); ``` 之後,請前往`/[root]/src/app/page.tsx`檔案並使用下面的程式碼匯入頂部的 CopilotKit 前端套件和樣式。 ``` import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import "@copilotkit/react-ui/styles.css"; ``` 然後使用`CopilotKit`包裝`CopilotSidebar`和`CodeTutorial`元件,如下所示。 `CopilotKit`元件指定 CopilotKit 後端端點 ( `/api/copilotkit/` ) 的 URL,而`CopilotSidebar`呈現應用程式內聊天機器人,您可以提示產生 UI 元件程式碼和實作教學。 ``` export default function Home() { return ( <> <Header /> <CopilotKit url="/api/copilotkit"> <CopilotSidebar instructions="Help the user generate code. Ask the user if to generate its tutorial." defaultOpen={true} labels={{ title: "Code & Tutorial Generator", initial: "Hi! 👋 I can help you generate code and its tutorial.", }}> <CodeTutorial /> </CopilotSidebar> </CopilotKit> </> ); } ``` 之後,執行開發伺服器並導航到 http://localhost:3000。您應該會看到應用程式內聊天機器人已整合到 UI 元件產生器中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ty4g6tuluhfiqtnnyxvg.png) ### **將 CopilotKit 後端加入博客** 在這裡,我將引導您完成將 UI 元件產生器與 CopilotKit 後端整合的過程,該後端處理來自前端的請求,並提供函數呼叫和各種 LLM 後端(例如 GPT)。 此外,我們將整合一個名為 Tavily 的人工智慧代理,它可以研究網路上的任何主題。 首先,在根目錄中建立一個名為`.env.local`的檔案。然後在保存`ChatGPT`和`Tavily` Search API 金鑰的檔案中加入下面的環境變數。 ``` OPENAI_API_KEY="Your ChatGPT API key" TAVILY_API_KEY="Your Tavily Search API key" ``` 若要取得 ChatGPT API 金鑰,請導覽至 https://platform.openai.com/api-keys。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mjl2g88iedd1n0qkd3ai.png) 若要取得 Tavilly Search API 金鑰,請導覽至 https://app.tavily.com/home ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m00kyux6biskw7xn2wec.png) 之後,轉到`/[root]/src/app`並建立一個名為`api`的資料夾。在`api`資料夾中,建立一個名為`copilotkit`的資料夾。 在`copilotkit`資料夾中,建立一個名為`research.ts`的檔案。然後導航到[該 Research.ts gist 文件](https://gist.github.com/TheGreatBonnie/58dc21ebbeeb8cbb08df665db762738c),複製程式碼,並將其新增至**`research.ts`**檔案中 接下來,在`/[root]/src/app/api/copilotkit`資料夾中建立一個名為`route.ts`的檔案。該文件將包含設定後端功能來處理 POST 請求的程式碼。它有條件地包括對給定主題進行研究的“研究”操作。 現在在文件頂部導入以下模組。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; // For backend functionality with CopilotKit. import { researchWithLangGraph } from "./research"; // Import a custom function for conducting research. import { AnnotatedFunction } from "@copilotkit/shared"; // For annotating functions with metadata. ``` 在上面的程式碼下面,定義一個執行時間環境變數和一個名為`researchAction`的函數,該函數使用下面的程式碼研究某個主題。 ``` // Define a runtime environment variable, indicating the environment where the code is expected to run. export const runtime = "edge"; // Define an annotated function for research. This object includes metadata and an implementation for the function. const researchAction: AnnotatedFunction<any> = { name: "research", // Function name. description: "Call this function to conduct research on a certain topic. Respect other notes about when to call this function", // Function description. argumentAnnotations: [ // Annotations for arguments that the function accepts. { name: "topic", // Argument name. type: "string", // Argument type. description: "The topic to research. 5 characters or longer.", // Argument description. required: true, // Indicates that the argument is required. }, ], implementation: async (topic) => { // The actual function implementation. console.log("Researching topic: ", topic); // Log the research topic. return await researchWithLangGraph(topic); // Call the research function and return its result. }, }; ``` 然後在上面的程式碼下加入下面的程式碼來定義處理POST請求的非同步函數。 ``` // Define an asynchronous function that handles POST requests. export async function POST(req: Request): Promise<Response> { const actions: AnnotatedFunction<any>[] = []; // Initialize an array to hold actions. // Check if a specific environment variable is set, indicating access to certain functionality. if (process.env.TAVILY_API_KEY) { actions.push(researchAction); // Add the research action to the actions array if the condition is true. } // Instantiate CopilotBackend with the actions defined above. const copilotKit = new CopilotBackend({ actions: actions, }); // Use the CopilotBackend instance to generate a response for the incoming request using an OpenAIAdapter. return copilotKit.response(req, new OpenAIAdapter()); } ``` 如何產生 UI 元件 ---------- 現在轉到您之前整合的應用程式內聊天機器人,並給它一個提示,例如「產生聯絡表單」。 生成完成後,您應該會看到生成的聯絡表單元件及其實作教程,如下所示。您也可以使用嵌入式程式碼編輯器修改產生的程式碼。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/43t9oauptomio4cy1gwr.png) ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/297vxxiqti56ydevfmyl.png) 恭喜!您已完成本教學的專案。 結論 -- [CopilotKit](https://copilotkit.ai/)是一款令人難以置信的工具,可讓您在幾分鐘內將 AI Copilot 加入到您的產品中。無論您是對人工智慧聊天機器人和助理感興趣,還是對複雜任務的自動化感興趣,CopilotKit 都能讓您輕鬆實現。 如果您需要建立 AI 產品或將 AI 工具整合到您的軟體應用程式中,您應該考慮 CopilotKit。 您可以在 GitHub 上找到本教學的源程式碼: <https://github.com/TheGreatBonnie/AIPoweredUIComponentsGenerator> --- 原文出處:https://dev.to/the_greatbonnie/ai-powered-frontend-ui-components-generator-nextjs-gpt4-langchain-copilotkit-1hac

可用於下一個專案的 30 多個強大 AI 庫

今天,我們將介紹 30 個或更多可以使用 AI 建置的專案。 所有專案都是開源的,因此您可以做出貢獻以使其變得更好。 有些專案可能擁有龐大的程式碼庫,但您可以從中獲得靈感並建立一個很酷的副專案。 相信我,如果這個清單沒有讓你感到驚訝,那麼沒有什麼會讓你感到驚訝:) 讓我們開始吧! ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o4ssxdcxcxmac945sj8x.gif) --- 1. [CopilotKit](https://go.copilotkit.ai/Anmol) - 在數小時內為您的產品提供 AI Copilot。 -------------------------------------------------------------------------- [![副駕駛套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzuxjfog2ldam3csrl62.png)](https://github.com/CopilotKit/CopilotKit) 將 AI 功能整合到 React 中是很困難的,這就是 Copilot 的用武之地。一個簡單快速的解決方案,可將可投入生產的 Copilot 整合到任何產品中! 您可以使用兩個 React 元件將關鍵 AI 功能整合到 React 應用程式中。它們還提供內建(完全可自訂)Copilot 原生 UX 元件,例如`<CopilotKit />` 、 `<CopilotPopup />` 、 `<CopilotSidebar />` 、 `<CopilotTextarea />` 。 開始使用以下 npm 指令。 ``` npm i @copilotkit/react-core @copilotkit/react-ui ``` Copilot Portal 是 CopilotKit 提供的元件之一,CopilotKit 是一個應用程式內人工智慧聊天機器人,可查看目前應用狀態並在應用程式內採取操作。它透過插件與應用程式前端和後端以及第三方服務進行通訊。 這就是整合聊天機器人的方法。 `CopilotKit`必須包裝與 CopilotKit 互動的所有元件。建議您也開始使用`CopilotSidebar` (您可以稍後切換到不同的 UI 提供者)。 ``` "use client"; import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import "@copilotkit/react-ui/styles.css"; export default function RootLayout({children}) { return ( <CopilotKit url="/path_to_copilotkit_endpoint/see_below"> <CopilotSidebar> {children} </CopilotSidebar> </CopilotKit> ); } ``` 您可以使用此[快速入門指南](https://docs.copilotkit.ai/getting-started/quickstart-backend)設定 Copilot 後端端點。 之後,您可以讓 Copilot 採取行動。您可以閱讀如何提供[外部上下文](https://docs.copilotkit.ai/getting-started/quickstart-chatbot#provide-context)。您可以使用`useMakeCopilotReadable`和`useMakeCopilotDocumentReadable`反應掛鉤來執行此操作。 ``` "use client"; import { useMakeCopilotActionable } from '@copilotkit/react-core'; // Let the copilot take action on behalf of the user. useMakeCopilotActionable( { name: "setEmployeesAsSelected", // no spaces allowed in the function name description: "Set the given employees as 'selected'", argumentAnnotations: [ { name: "employeeIds", type: "array", items: { type: "string" } description: "The IDs of employees to set as selected", required: true } ], implementation: async (employeeIds) => setEmployeesAsSelected(employeeIds), }, [] ); ``` 您可以閱讀[文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea)並查看[演示影片](https://github.com/CopilotKit/CopilotKit?tab=readme-ov-file#demo)。 您可以輕鬆整合 Vercel AI SDK、OpenAI API、Langchain 和其他 LLM 供應商。您可以按照本[指南](https://docs.copilotkit.ai/getting-started/quickstart-chatbot)將聊天機器人整合到您的應用程式中。 基本概念是在幾分鐘內建立可用於基於 LLM 的應用程式的 AI 聊天機器人。 用例是巨大的,作為開發人員,我們絕對應該在下一個專案中嘗試使用 CopilotKit。 CopilotKit 在 GitHub 上擁有超過 5700 顆星,發布了 200 多個版本,這意味著它們不斷改進。 https://go.copilotkit.ai/Anmol Star CopilotKit ⭐️ --- 2. [AgentGPT](https://github.com/reworkd/AgentGPT) - 組裝、配置和部署自主 AI 代理程式。 ------------------------------------------------------------------------ ![代理GPT](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnc918anlnbbymwep8xv.png) AgentGPT 可讓您設定和部署自主 AI 代理程式。 它將嘗試透過思考要完成的任務、執行任務並從結果中學習來實現目標:) 它是使用以下方式建構的: - 引導:create-t3-app + FastAPI-模板。 - 框架:Nextjs 13 + Typescript + FastAPI - 驗證:Next-Auth.js - ORM:Prisma 和 SQLModel。 - 資料庫:Planetscale。 - 樣式:TailwindCSS + HeadlessUI。 - 架構驗證:Zod + Pydantic。 - 法學碩士工具:Langchain。 開始使用本[指南](https://github.com/reworkd/AgentGPT?tab=readme-ov-file#getting-started-rocket)在本地安裝它。 您可以查看該應用程式的[演示](https://github.com/reworkd/AgentGPT?tab=readme-ov-file#-demo)並查看[即時網站](https://agentgpt.reworkd.ai/)。 ![示範](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v17lz12cn58ousqbiiyg.gif) 他們在 GitHub 上擁有 29k+ 顆星,並且正在發布`v1`版本。 https://github.com/reworkd/AgentGPT 明星 AgentGPT ⭐️ --- 3.[私人 GPT](https://github.com/zylon-ai/private-gpt) - 無需網路即可詢問有關您文件的問題。 ------------------------------------------------------------------------ ![私有GPT](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0nshjqmm5xq6kgqkgfdc.png) PrivateGPT 是一個可立即投入生產的 AI 專案,即使在沒有網路連線的情況下,您也可以使用大型語言模型 (LLM) 的功能來詢問有關文件的問題。 100% 私有意味著任何時候都沒有資料離開您的執行環境。 API 分為兩個邏輯區塊: A。高級 API,抽象化了 RAG(檢索增強生成)管道實現的所有複雜性: - 文件攝取:內部管理文件解析、分割、元資料擷取、嵌入產生和儲存。 - 使用所攝取文件中的上下文進行聊天和完成:抽像上下文檢索、提示工程和回應產生。 b.低階 API,允許高階用戶實現複雜的管道: - 嵌入生成:基於一段文字。 - 上下文區塊檢索:給定查詢,從攝取的文件中傳回最相關的文字區塊。 您可以閱讀[安裝指南](https://docs.privategpt.dev/installation/getting-started/installation)來開始。 您可以閱讀[文件](https://docs.privategpt.dev/overview/welcome/introduction)以及所涉及的[詳細架構](https://github.com/zylon-ai/private-gpt?tab=readme-ov-file#-architecture)。 PrivateGPT 現在正在發展成為產生 AI 模型和原語的網關,包括補全、文件攝取、RAG 管道和其他低階建置塊。 他們在 GitHub 上擁有超過 51,000 顆星,並且發展迅速。 https://github.com/zylon-ai/private-gpt 明星私人 GPT ⭐️ --- 4. [Instrukt](https://github.com/blob42/Instrukt) - 終端機中整合人工智慧。 --------------------------------------------------------------- ![指示](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wsk64pf5yuosui91tmz9.png) Instrukt是一個基於終端的AI整合環境。它提供了一個平台,用戶可以: - 建立並指導模組化人工智慧代理。 - 產生問答的文件索引。 - 建立工具並將其附加到任何代理程式。 用自然語言指導它們,並且為了安全起見,在安全容器(目前使用 Docker 實作)中執行它們,以在其專用的沙盒空間中執行任務。 使用`Langchain` 、 `Textual`和`Chroma`建構。 開始使用以下命令。 ``` pip install instrukt[all] ``` ![指示](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r3aza7hnlji7hbi2o0js.gif) 有許多令人興奮的功能,例如: - 基於終端的介面,讓強力鍵盤使用者無需離開鍵盤即可指示 AI 代理。 - 對您的資料建立索引並讓代理程式檢索它以進行問答。您可以使用簡單的 UI 建立和組織索引。 - 索引建立將自動偵測程式語言並相應地優化拆分/分塊策略。 - 在安全的 Docker 容器內執行代理程式以確保安全和隱私。 - 整合的 REPL-Prompt 可實現與代理程式的快速交互,以及用於開發和測試的快速回饋循環。 - 您可以使用自訂命令自動執行重複任務。它還具有內建的提示/聊天歷史記錄。 您可以閱讀有關所有[功能的](https://github.com/blob42/Instrukt?tab=readme-ov-file#features)資訊。 您可以閱讀[安裝指南](https://blob42.github.io/Instrukt/install.html)。 您還可以使用內建的 IPython 控制台來除錯和內省代理,這是一個簡潔的小功能。 ![控制台除錯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qaan8np68e3fk1yueexm.png) Instrukt 已獲得 AGPL 許可證,這意味著任何人都可以將其用於任何目的。 可以肯定地說,Instrukt 是您觸手可及的終端人工智慧指揮官。 這是一個新專案,因此他們在 GitHub 上有大約 200 多顆星,但用例非常好。 https://github.com/blob42/Instrukt 舊指令 ⭐️ --- 5. [Mac 上的語音助理](https://github.com/chidiwilliams/GPT-Automator)- 您的語音控制 Mac 助理。 ------------------------------------------------------------------------------- ![GPT自動機](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rdzv06jnr3z33s7qll5k.png) 您的語音控制 Mac 助理。 GPT Automator 可讓您使用語音在 Mac 上執行任務。例如,打開應用程式、尋找餐廳、綜合資訊。太棒了:D 它是在倫敦黑客馬拉松期間建構的。 它有兩個主要部分: A。語音命令:它使用本地執行的 Whisper(Buzz 的一個分支)來產生命令。 b.命令到行動:您向配備了我們編寫的自訂工具的 LangChain 代理程式發出命令。這些工具包括使用 AppleScript 控制電腦的作業系統以及使用 JavaScript 控制活動瀏覽器。最後,就像任何優秀的人工智慧一樣,我們讓代理商使用 AppleScript 說出最終結果「{Result}」(如果您以前沒有使用過,請嘗試在 Mac 終端機中輸入「Hello World!」)。 我們製作了一個自訂工具,讓法學碩士使用 AppleScript 控制電腦。提示符是文件字串: ``` @tool def computer_applescript_action(apple_script): """ Use this when you want to execute a command on the computer. The command should be in AppleScript. Here are some examples of good AppleScript commands: Command: Create a new page in Notion AppleScript: tell application "Notion" activate delay 0.5 tell application "System Events" to keystroke "n" using {{command down}} end tell ... Write the AppleScript for the Command: Command: """ p = subprocess.Popen(['osascript', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate(applescript.encode('utf-8')) if p.returncode != 0: raise Exception(stderr) decoded_text = stdout.decode("utf-8") return decoded_text ``` 如果您想知道它是如何運作的,GPT Automator 使用 OpenAI 的 Whisper 將您的音訊輸入轉換為文字。然後,它使用LangChain Agent 選擇一組操作,包括使用OpenAI 的GPT-3(“text-davinci-003”)從提示符號產生AppleScript(用於桌面自動化)和JavaScript(用於瀏覽器自動化)命令,然後執行產生的腳本。 請記住,這不適用於生產用途。該專案執行從自然語言產生的程式碼,可能容易受到提示注入和類似的攻擊。這項工作是作為概念驗證而進行的。 您可以閱讀[安裝指南](https://github.com/chidiwilliams/GPT-Automator?tab=readme-ov-file#instructions)。 讓我們看看一些提示及其作用: ✅ 求計算結果。 > 提示:“2 + 2 是什麼?” 它將編寫 AppleScript 開啟計算器並輸入 5 \* 5。 ✅ 尋找附近的餐廳。 > 提示:“查找我附近的餐廳” 它將打開 Chrome,谷歌搜尋附近的餐廳,解析頁面,然後返回最上面的結果。有時它很厚顏無恥,反而會打開谷歌地圖結果並說「最好的餐廳是谷歌地圖頁面頂部的餐廳」。其他時候,它會打開 Google 上的頂部連結 - 並卡在 Google 可存取性頁面上... 以下是執行時列印到終端的內容: ``` Command: Find a great restaurant near Manchester. > Entering new AgentExecutor chain... I need to search for a restaurant near Manchester. Action: chrome_open_url Action Input: https://www.google.com/search?q=restaurant+near+Manchester Observation: Thought: I need to read the page Action: chrome_read_the_page Action Input: Observation: Accessibility links Skip to main content ... # Shortned for brevity Dishoom Manchester 4.7 (3.3K) · £££ · Indian 32 Bridge St · Near John Rylands Library Closes soon ⋅ 11 pm Stylish eatery for modern Indian fare San Carlo 4.2 (2.8K) · £££ · Italian 42 King St W · Near John Rylands Library Closes soon ⋅ 11 pm Posh, sceney Italian restaurant Turtle Bay Manchester Northern Quarter 4.7 Thought: I now know the final answer Final Answer: The 15 best restaurants in Manchester include El Gato Negro, Albert's Schloss, The Refuge, Hawksmoor, On The Hush, Dishoom, Banyan, Zouk Tea Room & Grill, Edison Bar, MyLahore Manchester, Turtle Bay Manchester Northern Quarter, San Carlo, The Black Friar, Mana, and Tast Cuina Catalana. ``` 我不能保證這些餐廳值得,請自行承擔風險。哈哈! ✅ 如果您要求 GPT Automator 擦除您的計算機,它會的。 是的,如果您要求的話,它會擦除您的電腦! 我內心的自我尖叫著要這麼做:) 您可以在這裡查看完整的演示! https://www.loom.com/share/7bfa82c604f3412fbbb04191ce2ae12f 您可以在[Chidi 的部落格](https://chidiwilliams.com/posts/gpt-automator)上閱讀更多內容。 它更像是一個業餘專案,因此他們在 GitHub 上有大約 200 個 star,但它非常酷。 https://github.com/chidiwilliams/GPT-Automator 明星 GPT Automator ⭐️ --- 6. [Flowise](https://github.com/FlowiseAI/Flowise) - 拖放 UI 來建立您的客製化 LLM 流程。 --------------------------------------------------------------------------- ![流塞伊](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r5bp43nil764fhe4a05z.png) Flowise 是一款開源 UI 視覺化工具,用於建立客製化的 LLM 編排流程和 AI 代理程式。 開始使用以下 npm 指令。 ``` npm install -g flowise npx flowise start OR npx flowise start --FLOWISE_USERNAME=user --FLOWISE_PASSWORD=1234 ``` 這就是整合 API 的方式。 ``` import requests url = "/api/v1/prediction/:id" def query(payload): response = requests.post( url, json = payload ) return response.json() output = query({ question: "hello!" )} ``` ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ahk2ovjrpq1qk3r5pfot.png) 您可以閱讀[文件](https://docs.flowiseai.com/)。 ![流程化人工智慧](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trkltpn5lk1y1pte0smd.png) 雲端主機不可用,因此您必須使用這些[說明](https://github.com/FlowiseAI/Flowise?tab=readme-ov-file#-self-host)自行託管。 讓我們探討一些用例: - 假設您有一個網站(可以是商店、電子商務網站或部落格),並且您希望廢棄該網站的所有相關連結,並讓法學碩士回答您網站上的任何問題。您可以按照此[逐步教學](https://docs.flowiseai.com/use-cases/web-scrape-qna)來了解如何實現相同的目標。 ![刮刀](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e91sz2mga5wvc0x2hp2g.png) - 您還可以建立一個自訂工具,該工具將能夠呼叫 Webhook 端點並將必要的參數傳遞到 Webhook 主體中。請依照本[指南](https://docs.flowiseai.com/use-cases/webhook-tool)使用 Make.com 建立 Webhook 工作流程。 ![網路鉤子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ckyivo9dvue461jc9pv4.png) 還有許多其他用例,例如建立 SQL QnA 或與 API 互動。 FlowiseAI 在 GitHub 上擁有超過 27,500 個 Star,並擁有超過 10,000 個分叉,因此具有良好的整體比率。 https://github.com/FlowiseAI/Flowise 明星 Flowise ⭐️ --- 7. [Twitter Agent](https://github.com/ahmedbesbes/media-agent) - 從社群媒體抓取資料並使用 Langchain 與其聊天。 --------------------------------------------------------------------------------------------- ![推特代理](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g8umoek3meg2tjxw9jna.png) Media Agent 抓取 Twitter 和 Reddit 提交的內容,對其進行總結,並在互動式終端中與它們聊天。這麼酷的概念! 您可以閱讀[說明](https://github.com/ahmedbesbes/media-agent?tab=readme-ov-file#run-the-app-locally)以在本地安裝它。 它是使用以下方式建構的: - Langchain 🦜 用於建構和撰寫法學碩士。 - ChromaDB 用於儲存向量(也稱為嵌入)並查詢它們以建立對話機器人。 - Tweepy 連接到您的 Twitter API 並提取推文和元資料。 - Praw 連接到 Reddit API。 - Rich 建造了一個很酷的終端 UX/UI。 - 管理依賴關係的詩。 一些很棒的功能: - 代表您從使用者帳戶清單或關鍵字清單中抓取推文/提交內容。 - 使用 OpenAI 嵌入推文/提交內容。 - 建立推文/提交內容的摘要並提供需要回答的潛在問題。 - 在推文之上打開聊天會話。 - 儲存對話及其元資料。 - 豐富的終端使用者介面和日誌記錄功能。 您可以觀看演示! https://www.loom.com/share/f4954e7d34ef4b7b8491e2bf910e8521 它在 GitHub 上有近 100 顆星,並且不再維護。您可以用它來建造更好的東西。 https://github.com/ahmedbesbes/media-agent 明星 Twitter 代理商 ⭐️ --- 8. [GPT 遷移](https://github.com/joshpxyne/gpt-migrate)- 輕鬆將程式碼庫從一種框架或語言遷移到另一種框架或語言。 ---------------------------------------------------------------------------------- ![GPT 遷移](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ullej3qz57t3l4qneyru.png) 如果您曾經面臨將程式碼庫遷移到新框架或語言的痛苦,那麼這個專案適合您。 我想我們都同意我們在某個時候需要這個。您也可以使用工作流程來完成此操作,據我所知,Stripe 曾經將其整個 JS 程式碼庫轉換為 TS。 遷移是一個成本高、乏味且重要的問題。 不要盲目相信當前版本,請負責任地使用它。另請注意,成本可能會迅速增加,因為 GPT-Migrate 旨在編寫(並可能重寫)整個程式碼庫。 您可以使用 Poetry[安裝](https://github.com/joshpxyne/gpt-migrate?tab=readme-ov-file#-installation-using-poetry)它並了解[它的工作原理](https://github.com/joshpxyne/gpt-migrate?tab=readme-ov-file#-how-it-works)。 > 請注意。 GPT-Migrate 目前處於開發 alpha 階段,尚未準備好投入生產使用。例如,在相對簡單的基準測試中,它在約 50% 的時間內順利通過 Python 或 JavaScript 等「簡單」語言,並且在沒有人工幫助的情況下無法通過 C++ 或 Rust 等更複雜的語言。 您可以在這裡觀看演示! ![GPT 遷移](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/megapc2dsnb6qlcl0dy4.gif) 他們在 GitHub 上有 6500+ 顆星,最後一次提交是 6 個月前,所以我認為它不再被維護了! https://github.com/joshpxyne/gpt-migrate 明星 GPT 遷移 ⭐️ --- 9. [Plandex](https://github.com/plandex-ai/plandex) - 用於使用法學碩士建置複雜的真實世界軟體的人工智慧編碼引擎。 ----------------------------------------------------------------------------------- ![普蘭迪克斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9c98v9qntshph3wue4fr.png) Plandex 使用長時間執行的代理程式來完成跨多個檔案且需要多個步驟的任務。它將大任務分解為更小的子任務,然後實現每個子任務,一直持續到完成工作為止。 它可以幫助您處理積壓的工作,使用不熟悉的技術,擺脫困境,並花更少的時間在無聊的事情上。 您可以在這裡查看演示! https://vimeo.com/926634577 變更會累積在受保護的沙箱中,以便您可以在自動將它們套用到專案文件之前查看它們。內建版本控制可讓您輕鬆返回並嘗試不同的方法。分支允許您嘗試多種方法並比較結果。 您可以在終端機中有效地管理上下文。輕鬆將檔案或整個目錄新增至上下文中,並在工作時自動更新它們,以便模型始終具有專案的最新狀態。 Plandex 依賴 OpenAI API,並且需要`OPENAI_API_KEY`環境變數。 Plandex 支援 Mac、Linux、FreeBSD 和 Windows。它從沒有依賴關係的單一二進位檔案執行。 您甚至可以嘗試不同的模型和模型設置,然後比較結果。 您可以閱讀[安裝說明](https://github.com/plandex-ai/plandex?tab=readme-ov-file#install)。 Plandex Cloud 是使用 Plandex 最簡單、最可靠的方式。當您使用 plandex new 建立第一個計劃時,系統會提示您開始匿名試用(無需電子郵件)。試用帳戶僅限 10 個計劃,每個計劃有 10 個 AI 模型回复。 Plandex Cloud 帳戶目前是免費的,這是一件好事。 Plandex 在 GitHub 上擁有 8k+ 顆星,並使用 Go 建造。 https://github.com/plandex-ai/plandex 明星PLandex ⭐️ --- 10. [SQL Translator](https://github.com/whoiskatrin/sql-translator) - 使用人工智慧將自然語言查詢轉換為 SQL 程式碼的工具。 -------------------------------------------------------------------------------------------------- ![SQL翻譯器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ghpgh4gvpdfiuj2qbat.png) 我試圖建立一個類似的專案,發現它已經存在。 該工具旨在讓任何人都可以輕鬆地將 SQL(結構化查詢語言)命令轉換為自然語言,反之亦然。 SQL 是一種用於管理和操作關聯式資料庫中的資料的程式語言,雖然它是一個強大的工具,但它也可能非常複雜且難以理解。 另一方面,自然語言是我們在日常生活中說和寫的語言,對於不熟悉技術術語的人來說,它通常是首選的溝通方式。 透過 SQL 和自然語言翻譯器,您無需成為 SQL 專家即可了解資料庫中發生的情況或編寫 SQL 查詢。您只需用自然語言輸入查詢即可取得對應的 SQL 程式碼,反之亦然。 其中一些功能是: - 深色模式。 - 小寫/大寫切換。 - 複製到剪貼簿。 - SQL 語法高亮。 - 模式意識(測試版)。 - 查詢歷史記錄。 你可以閱讀 [安裝說明](https://github.com/whoiskatrin/sql-translator?tab=readme-ov-file#%EF%B8%8F-installation),它非常簡單,因為它使用 Nextjs。 此查詢適合您。哈哈! ![酷查詢](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eef11xrahbmv945xvpm7.png) SQL Translator 在 GitHub 上有 4k star,是使用 TypeScript 建構的。 https://github.com/whoiskatrin/sql-translator 明星 SQL 翻譯機 ⭐️ --- 11. [WingmanAI](https://github.com/e-johnstonn/wingmanAI) - 音訊即時轉錄,與 ChatGPT 整合。 -------------------------------------------------------------------------------- ![僚機人工智慧](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/slrhmt949vr7gqdmgi3h.png) WingmanAI 是一款功能強大的工具,可與系統和麥克風音訊的即時轉錄進行互動。該工具由 ChatGPT 提供支援,可讓您與腳本即時交互,作為機器人的廣泛記憶體基礎,提供獨特的通訊平台。 當您載入指定人員的記錄時,機器人可以回答有關過去對話的問題。 您可以閱讀[安裝說明](https://github.com/e-johnstonn/wingmanAI?tab=readme-ov-file#installation)。 您可以在這裡觀看演示! ![示範](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w325vc51fys8gebrcb02.gif) 一些簡潔的功能是: - WingmanAI 可以轉錄系統輸出和麥克風輸入音頻,讓您以易於閱讀的格式查看即時轉錄。 - 您可以與 ChatGPT 支援的機器人聊天,該機器人會即時讀取您的文字記錄。 - 機器人以令牌有效的方式維護對話記錄,因為只有當前的文字區塊會傳遞給機器人。 - WingmanAI 讓您可以保存成績單以供將來使用。您可以稍後隨時加載它們,並且對機器人進行的任何查詢都將與保存的轉錄本的向量資料庫交叉引用,從而為機器人提供更豐富的上下文。 - 您可以繼續附加到已儲存的記錄中,隨著時間的推移建立一個龐大的資料庫供機器人從中提取。 它在 GitHub 上有 420 個星,並且不再維護。 https://github.com/e-johnstonn/wingmanAI 明星 WingmanAI ⭐️ --- 12. [Lively](https://github.com/rocksdanister/lively) - 允許使用者設定動畫桌面桌布和螢幕保護程式。 ----------------------------------------------------------------------------- ![活潑](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60tld1a857herh12r5ci.png) 這只是為了好玩,我們可以使用程式碼學到很多關於它是如何完成的。 你可以看看這個[影片](https://www.pexels.com/video/blue-texture-abstract-leaves-7710243/),看看它看起來有多瘋狂。 ![風俗](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kb2ll571uc2jd2xrpmph.png) 他們提供[三種類型的壁紙,](https://github.com/rocksdanister/lively?tab=readme-ov-file#types-of-wallpapers)包括影片/GIF、網頁和應用程式/遊戲。 它基於 C# 和 live 支援的一些很酷的功能建置: 1. Lively 可以透過終端機的[命令列參數](https://github.com/rocksdanister/lively/wiki/Command-Line-Controls)進行控制。您可以將其與其他語言(例如 Python 或腳本軟體 AutoHotKey)整合。 2. 一組強大的[API](https://github.com/rocksdanister/lively/wiki/API) ,供開發人員建立互動式壁紙。取得硬體讀數、音訊圖表、音樂資訊等。 3. 當電腦上執行全螢幕應用程式/遊戲時(~0% CPU、GPU 使用率),桌布播放會暫停。 4. 您還可以利用[機器學習推理](https://github.com/rocksdanister/lively/wiki/Machine-Learning)來建立動態壁紙。您可以預測任何 2D 影像與相機的距離並產生類似 3D 的視差效果。酷:D 我見過很多人使用它,其中許多人甚至不知道它是開源的。 您可以使用[安裝程式](https://github.com/rocksdanister/lively/releases/download/v2.0.7.4/lively_setup_x86_full_v2074.exe)或透過[Microsoft Store](https://www.microsoft.com/store/productId/9NTM2QC6QWS7?ocid=pdpshare)下載它。 它是 2023 年 Microsoft Store 的獲勝者。 它在 GitHub 上擁有 13k+ Stars,有 60 個版本。 https://github.com/rocksdanister/lively 明星活潑 ⭐️ --- 13. [RestGPT](https://github.com/Yifan-Song793/RestGPT) - 基於 LM 的自主代理透過 RESTful API 控制應用程式。 ------------------------------------------------------------------------------------------- ![休息GPT](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lyp7goco6awn2l4uttww.png) 這項工作旨在建立一個基於大型語言模型的自主代理 RestGPT,以控制現實世界的應用程式,例如電影資料庫和音樂播放器。為了實現這一目標,我們將法學碩士與 RESTful API 連接起來,並解決規劃、API 呼叫和回應解析的實際挑戰。為了全面評估 RestGPT 的效能,我們提出了 RestBench,這是一個高品質的基準測試,由兩個真實場景和具有黃金解決方案路徑的人工註釋指示組成。 RestGPT採用迭代式從粗到精的線上規劃框架,並使用執行器呼叫RESTful API。以下是 RestGPT 的概述。 ![在職的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/17p05syighh3llbmr1fk.png) 您可以閱讀[文件](https://github.com/Yifan-Song793/RestGPT?tab=readme-ov-file#data)以使用 RestBench 評估 RestGPT 的效能。 使用 TMDB 電影資料庫搜尋 Sofia Coppola 執導的電影數量的範例。 ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/toh8k55yhb7c6t4oq0j7.gif) 您可以閱讀康乃爾大學發表的程式碼研究論文: [RestGPT - Connecting Large Language Models with Real-World RESTful APIs](https://arxiv.org/abs/2306.06624) 。 他們在 GitHub 上有 1.2k Stars,雖然不是很大,但涵蓋了一個很好的用例。 https://github.com/Yifan-Song793/RestGPT 明星 RestGPT ⭐️ --- 14. [ChatFiles](https://github.com/guangzhengli/ChatFiles) - 上傳您的檔案並與其對話。 ------------------------------------------------------------------------- ![聊天文件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lhimajsma8ijyzeknmlg.png) 文件聊天機器人 — 多個文件,由 GPT / Embedding 提供支援。你可以上傳任何文件並與之對話,考慮到他們使用了另一個著名的開源專案,UI 非常好。 它在底層使用 Langchain 和[Chatbot-ui](https://github.com/mckaywrigley/chatbot-ui) 。使用 Nextjs、TypeScript、Tailwind 和 Supabase(向量 DB)建構。 如果您想了解該方法和技術架構,那麼就在這裡! ![建築學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8zbn7h50k6gwxgz6rkaf.png) 此環境僅用於試用,支援最大檔案大小為 10 MB,這是一個缺點,如果您想要更大的大小,則可以[在本機安裝](https://github.com/guangzhengli/ChatFiles?tab=readme-ov-file#how-to-run-locally)。 他們提供了您可以使用的[入門問題](https://github.com/guangzhengli/ChatFiles/blob/main/doc/Example.md)。您可以查看[現場演示](https://chatfile.vectorhub.org/)。 他們在 GitHub 上有 3k star,並且發布了`v0.3`版本。 https://github.com/guangzhengli/ChatFiles 明星 ChatFiles ⭐️ --- 15. [MindsDB](https://github.com/mindsdb/mindsdb) - 從企業資料客製化人工智慧的平台。 -------------------------------------------------------------------- ![思維資料庫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i9q3jdswxdx6wqfk0vqw.png) MindsDB 是一個利用企業資料客製化人工智慧的平台。 透過 MindsDB,您可以利用資料庫、向量儲存或應用程式中的資料即時部署、服務和微調模型,以建立人工智慧驅動的應用程式 - 使用開發人員已知的通用工具。 借助 MindsDB 及其與資料來源和 AI/ML 框架的近[200 個集成](https://docs.mindsdb.com/integrations/data-overview),任何開發人員都可以使用其企業資料更快、更安全地自訂符合其目的的 AI。 ![MindsDB 的工作原理](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4q1gfmhq43gopdix03gr.png) 您可以閱讀[文件](https://docs.mindsdb.com/)和[快速入門指南](https://docs.mindsdb.com/quickstart-tutorial)來開始使用。 目前,他們總共支援[3 個使用 Mongo-QL、Python 和 JavaScript 的 SDK](https://docs.mindsdb.com/sdks/overview) 。 MindsDB 有多種應用程式,例如與眾多資料來源和 AI 框架集成,因此您可以輕鬆地將資料和 AI 結合在一起以建立和自動化自訂工作流程。 其他常見用例包括微調模型、聊天機器人、警報系統、內容生成、自然語言處理、分類、回歸和預測。閱讀有關[用例的](https://docs.mindsdb.com/use-cases/)更多訊息,每個用例都有一個包含一些資訊的架構圖。 ![用例](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wuhxzbioqh9a5s9f0w7s.png) 例如,MindsDB 的聊天機器人架構圖。您可以閱讀提供的所有[解決方案](https://github.com/mindsdb/mindsdb?tab=readme-ov-file#-get-started)及其 SQL 查詢範例。 ``` // SQL Query Example for Chatbot CREATE CHATBOT slack_bot USING database='slack',agent='customer_support'; ``` ![聊天機器人](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/otoqsro02ghqb709yglk.png) 只是為了告訴您總體的可能性,您可以查看[如何使用 AI + IoT 感測器資料預測氣溫](https://mindsdb.com/blog/how-to-forecast-air-temperatures-with-ai-iot-sensor-data)。令人興奮的權利:) ![心靈資料庫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/82wrjyrkch44taeurv1r.png) 他們在 GitHub 上擁有超過 21k 個 star,並且在`v24.4.3.0`上有超過 200 個版本。順便說一句,這是我第一次在任何版本中看到 4 個部分,因為我一直遵循語義版本。 https://github.com/mindsdb/mindsdb 明星 MindsDB ⭐️ --- 16. [Quivr](https://github.com/QuivrHQ/quivr) - 你的 GenAI 第二腦。 ------------------------------------------------------------- ![奎弗爾](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hl12fl88mdjmfkfath1t.png) Quivr,您的第二個大腦,利用 GenerativeAI 的力量成為您的私人助理!可以將其視為黑曜石,但增強了人工智慧功能。 ![統計資料](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5a27c2ubbmri0b2xlh1l.png) 您可以閱讀[安裝指南](https://github.com/QuivrHQ/quivr?tab=readme-ov-file#getting-started-)。 您可以閱讀[文件](https://docs.quivr.app/home/intro)並觀看[示範影片](https://github.com/QuivrHQ/quivr?tab=readme-ov-file#demo-highlights-)。 他們可以提供更好的免費套餐,但這足以在您端進行測試。 它在 GitHub 上擁有超過 30k 顆星,發布了 220 多個版本,這意味著它們正在不斷改進。 https://github.com/QuivrHQ/quivr 明星 Quivr ⭐️ --- 17.[動畫繪畫](https://github.com/facebookresearch/AnimatedDrawings)- 一種將兒童人物繪畫動畫化的方法。 --------------------------------------------------------------------------------- ![動畫圖畫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9pvpj68sum9xrqfz0s6n.gif) 我的意思是哇!這麼酷的概念。我不知道你怎麼想,但我真的很興奮。 這是 Facebook 的一個開源專案,主要用於研究目的,包含論文《 [A Method for Animating Children's Drawings of the Human Figure》](https://dl.acm.org/doi/10.1145/3592788)中描述的演算法的實作。 該專案已在 macOS Ventura 13.2.1 和 Ubuntu 18.04 上進行了測試。如果您在其他作業系統上安裝,則可能會遇到問題。 他們強烈建議在安裝 Animated Drawings 之前啟動 Python 虛擬環境。 閱讀有關[安裝說明](https://github.com/facebookresearch/AnimatedDrawings?tab=readme-ov-file#installation)以及如何快速入門的更多資訊。 您可以按照這個完整的指南來為[您的繪圖製作動畫](https://github.com/facebookresearch/AnimatedDrawings?tab=readme-ov-file#animating-your-own-drawing),包括如何在場景中加入多個角色、加入背景圖像以及更多令人興奮的事情。 他們在 GitHub 上擁有超過 10k 顆星,並且僅用於具有 MIT 許可的研究目的。 https://github.com/facebookresearch/AnimatedDrawings 明星動畫繪圖 ⭐️ --- 18.[背景移除器](https://github.com/nadermx/backgroundremover)- 讓您可以透過簡單的 CLI 使用 AI 從影像和影片中移除背景。 ------------------------------------------------------------------------------------------ ![背景去除劑](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v8bppslk45ci383wpman.png) 這是一個使用 AI 從圖像和影片中刪除背景的命令列工具。 首先從 pypi 安裝 backgroundremover。 ``` pip install --upgrade pip pip install backgroundremover ``` 也可以在不透過 pip 安裝的情況下執行它,只需克隆 git 以在本地啟動虛擬環境安裝要求並執行。 您可以使用的一些命令: - 從本機檔案圖像中刪除背景 ``` backgroundremover -i "/path/to/image.jpeg" -o "output.png" ``` - 從本地影片中刪除背景並將其覆蓋在圖像上 ``` backgroundremover -i "/path/to/video.mp4" -toi "/path/to/videtobeoverlayed.mp4" -o "output.mov" ``` 您可以檢查可透過 CLI 使用的所有[命令](https://github.com/nadermx/backgroundremover?tab=readme-ov-file#usage-as-a-cli)。 您甚至可以將它用作圖書館。 ``` from backgroundremover.bg import remove def remove_bg(src_img_path, out_img_path): model_choices = ["u2net", "u2net_human_seg", "u2netp"] f = open(src_img_path, "rb") data = f.read() img = remove(data, model_name=model_choices[0], alpha_matting=True, alpha_matting_foreground_threshold=240, alpha_matting_background_threshold=10, alpha_matting_erode_structure_size=10, alpha_matting_base_size=1000) f.close() f = open(out_img_path, "wb") f.write(img) f.close() ``` 您可以閱讀[安裝說明](https://github.com/nadermx/backgroundremover?tab=readme-ov-file#installation)並觀看[現場演示](https://www.backgroundremoverai.com/)。 > 輸入與輸出。 ![輸入影像](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0rwjaxxw460lugle5z2.png) 他們在 GitHub 上有 6k star,我們絕對可以用它來學習一些重要的概念。 https://github.com/nadermx/backgroundremover 明星背景去除器 ⭐️ --- 19. [Lobe Chat](https://github.com/lobehub/lobe-chat) - 現代設計的法學碩士/人工智慧聊天框架。 --------------------------------------------------------------------------- ![波瓣聊天](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ddxibf7xxx931tdoj1mn.png) 一個開源、現代設計的 ChatGPT/LLM UI/框架。 支援語音合成、多模式和可擴展(函數呼叫)插件系統。您可以一鍵部署您的私有 OpenAI。 ![旅行](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/39se198xal53r854sdps.png) 讓我們來看看 LobeChat 的一些令人興奮的功能: ✅ 多模式服務提供者支援。 ![多服務](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nodazgxel962wrp2hnvo.png) 他們將我們的支援擴展到多個模型服務提供者,而不是局限於單一服務提供者,為用戶提供更多樣化和豐富的對話選擇。 尋找他們支援的[10 多個模型服務提供者](https://lobehub.com/docs/usage/features/multi-ai-providers)的完整清單。 ✅ 市場助理。 ![助理市場](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/35z3kz2jr4mnxid9dwsg.png) 在LobeChat的[助手市場](https://lobehub.com/assistants)中,創作者可以發現一個充滿活力和創新的社區,匯集了許多精心設計的助手。這些助手不僅在工作場景中發揮著至關重要的作用,而且在學習過程中也提供了極大的便利。在這裡,每個人都可以貢獻自己的智慧,分享自己開發的助手。 ![市場](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ex23f2epblfp2cxtxbnl.png) 那裡有很多很棒的應用程式。哇! ✅ 模型視覺辨識。 ![模型視覺辨識](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fuxz350091223cj36dq7.png) LobeChat現在支援OpenAI的gpt-4-vision、Google Gemini Pro Vision、Zhipu GLM-4 Vision等具有視覺辨識能力的大型語言模型,使LobeChat具備多模態互動能力。用戶可以輕鬆地將圖片上傳或拖放到聊天框中,助理將能夠辨識圖片內容並據此進行智慧對話,打造更聰明、更多樣化的聊天場景。 ✅ 文字到圖像生成。 ![文字到圖像生成](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z2q6qzcy8anjgsg2381o.png) LobeChat 支援最新的文字到圖像生成技術,現在允許使用者在與助手對話時直接使用文字到圖像工具。透過利用 DALL-E 3、MidJourney 和 Pollinations 等 AI 工具的功能,助手現在可以將您的想法轉化為圖像。 ✅ 本地大語言模型 (LLM) 支援。 ![本地大語言模型 (LLM) 支援。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ucn4rpa4p2vb11hhvkn1.png) 借助 Ollama AI 強大的基礎設施和社區的協作努力,現在您可以在 LobeChat 中與本地 LLM(大型語言模型)進行對話! 透過執行以下 Docker 指令,您可以在 LobeChat 中體驗與本機 LLM 的對話。 ``` docker run -d -p 3210:3210 -e OLLAMA_PROXY_URL=http://host.docker.internal:11434/v1 lobehub/lobe-chat ``` ✅ 漸進式網頁應用程式 (PWA)。 ![漸進式網頁應用程式 (PWA)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sccmha74iz01rr12gphr.png) 他們採用了漸進式 Web 應用程式 PWA 技術,這是一種現代 Web 技術,可將 Web 應用程式提升到接近本機應用程式的體驗。透過 PWA,LobeChat 可以在桌面和行動裝置上提供高度優化的使用者體驗,同時保持輕量級和高效能的功能。 ✅ 自訂主題。 ![自訂主題](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7cl73pplbor4z1381kdm.png) LobeChat在介面設計上非常注重個人化的使用者體驗,因此引入了靈活多樣的主題模式,包括白天的淺色模式和夜間的深色模式。 除了主題模式切換之外,我們還提供了一系列顏色自訂選項,讓使用者可以根據自己的喜好調整應用程式的主題顏色。 了解所有[功能和用例](https://lobehub.com/docs/usage/start)。 您可以自行託管或使用 docker 部署它。 lobe chat 的[生態系統](https://github.com/lobehub/lobe-chat/tree/main?tab=readme-ov-file#-ecosystem)提供了 4 個軟體包: `lobehub/ui` 、 `lobehub/icons` 、 `lobehub/tts`和`lobehub/lint` 。 他們還提供[插件市場](https://lobehub.com/plugins),您可以在其中找到許多有用的插件,這些插件可用於引入新的函數呼叫,甚至是呈現訊息結果的新方法。如果你想開發自己的插件,請參考 wiki 中的[📘插件開髮指南](https://lobehub.com/docs/usage/plugins/development)。 ![插件市場](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uqtxt31vc42uwnw2ukgr.png) 您可以閱讀[文件](https://lobehub.com/docs/usage/start)。 您可以查看[現場演示](https://chat-preview.lobehub.com/chat)。它太酷了! ![演示快照](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xe3ngshtwpps2kmpu98f.png) 他們在 GitHub 上擁有超過 28k 顆星,發布了 500 多個版本。 https://github.com/lobehub/lobe-chat 星瓣聊天 ⭐️ --- 20.[微代理](https://github.com/aymenfurter/microagents)- 能夠自我編輯提示的代理。 ------------------------------------------------------------------ ![微代理](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nuxv03dgb03s04dkmkm9.png) 它是一個實驗框架,用於動態建立自我改進的代理來回應任務。 微代理代表了一種建立自我改進代理的新方法。小型的微服務大小(因此稱為微代理)代理是根據用戶分配給助手的任務動態生成的,評估其功能,並在成功驗證後存儲以供將來重用。 這使得跨聊天會話的學習成為可能,使系統能夠獨立推斷任務執行的方法。 這是使用`Python` 、 `OpenAI's GPT-4 Turbo`和`Text-Embedding-Ada-002`建構的。 您可以閱讀[安裝說明](https://github.com/aymenfurter/microagents?tab=readme-ov-file#installation)。他們提到您應該擁有一個可以存取 gpt-4-turbo 和 text-embedding-ada-002 的 OpenAI 帳戶。 讓我們看一個獲取天氣預報代理的範例。 ``` You are an adept weather informant. Fetch the weather forecast by accessing public API data using this Python code snippet: ``python import requests import json def fetch_weather_forecast(location, date): response = requests.get(f"https://api.met.no/weatherapi/locationforecast/2.0/compact?lat={location[0]}&lon={location[1]}") weather_data = response.json() for day_data in weather_data['properties']['timeseries']: if date in day_data['time']: print(day_data['data']['instant']['details']) break `` # Example usage: fetch_weather_forecast((47.3769, 8.5417), '2024-01-22T12:00:00Z') Note: Replace the (47.3769, 8.5417) with the actual latitude and longitude of the location and the date string accordingly. ``` 如果您想知道如何建立代理,那麼此架構圖將對此進行解釋。 ![圖表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7oi4fbt6e5qauqo293qt.png) 您可以看到[工作演示](https://github.com/aymenfurter/microagents?tab=readme-ov-file#demo)。 他們在 GitHub 上有大約 700 顆星,值得一看。 https://github.com/aymenfurter/microagents 明星微代理 ⭐️ --- 21. [GPT-4 & LangChain](https://github.com/mayooear/gpt4-pdf-chatbot-langchain) - 用於大型 PDF 文件的 GPT4 和 LangChain 聊天機器人。 -------------------------------------------------------------------------------------------------------------------------- ![聊天架構](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0pe0xehimhyw2mfubzu9.png) 這可用於新的 GPT-4 API 來為多個大型 PDF 檔案建立 chatGPT 聊天機器人。 該系統是使用 LangChain、Pinecone、Typescript、OpenAI 和 Next.js 建構的。 LangChain 是一個簡化可擴展 AI/LLM 應用程式和聊天機器人開發的框架。 Pinecone 用作向量存儲,用於以文字格式儲存嵌入和 PDF,以便以後檢索類似文件。 您可以閱讀涉及複製、安裝依賴項和設定環境 API 金鑰的[開發指南](https://github.com/mayooear/gpt4-pdf-chatbot-langchain?tab=readme-ov-file#development)。 您可以觀看[YouTube 影片](https://www.youtube.com/watch?v=ih9PBGVVOO4),了解如何遵循和使用它。 他們在 GitHub 上擁有 14k+ Stars,僅提交了 34 次。在您的下一個人工智慧應用程式中嘗試! https://github.com/mayooear/gpt4-pdf-chatbot-langchain 明星 GPT-4 和 Langchain ⭐️ --- 22. [Buzz](https://github.com/chidiwilliams/buzz) - 在您的個人電腦上離線轉錄和翻譯音訊。 ---------------------------------------------------------------------- ![嗡嗡聲](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qdi1olu9ogarzxdc3ct9.png) 使用 OpenAI 的 Whisper 的強大功能在您的個人電腦上離線轉錄和翻譯音訊。 Buzz 甚至出現在[App Store](https://apps.apple.com/us/app/buzz-captions/id6446018936?mt=12&itsct=apps_box_badge&itscg=30200) 。取得 Buzz 的 Mac 原生版本,具有更簡潔的外觀、音訊播放、拖放匯入、文字記錄編輯、搜尋等功能。 您可以閱讀[安裝說明](https://chidiwilliams.github.io/buzz/docs/installation)。 令人興奮的功能: - 匯入音訊和視訊檔案並將文字記錄匯出為 TXT、SRT 和 VTT(演示)。 - 從電腦麥克風轉錄和翻譯為文字(資源密集且可能不是即時的。 - 它可在 Mac、Windows 和 Linux 上使用。 - 還有一個[CLI](https://chidiwilliams.github.io/buzz/docs/cli)選項。 在這裡查看演示! https://www.loom.com/share/564b753eb4d44b55b985b8abd26b55f7 您可以閱讀[文件](https://chidiwilliams.github.io/buzz/docs)。 它們在 GitHub 上擁有近 10k star,並且自兩週前上次提交以來仍在維護中。 https://github.com/chidiwilliams/buzz 明星嗡嗡聲 ⭐️ --- 23. [Deepgram](https://github.com/deepgram) - 將語音 AI 建置到您的應用程式中。 ---------------------------------------------------------------- ![深度圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/32enxrtcwqk6g81eazay.png) 從新創公司到 NASA,Deepgram API 每天都用於轉錄和理解數百萬分鐘的音訊。快速、準確、可擴展且經濟高效。 它為開發人員提供語音到文字和音訊智慧模型。 ![深度圖選項](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rdc3tqg7fvt3sw6ktle7.png) 儘管他們有免費增值模式,但免費套餐的限制足以讓您入門。 可視化效果更上一層樓。您可以檢查即時串流媒體回應或音訊檔案並比較音訊的智慧程度。 ![串流媒體](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4wcvzzrqzn94gxe594hf.png) ![情緒分析](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uw6wkhzg7g6vgq7lphri.png) 您可以閱讀[文件](https://developers.deepgram.com/docs/introduction)。 您也可以閱讀 Deepgram 撰寫的關於[如何將語音辨識新增至您的 React 和 Node.js 專案的範例部落格](https://deepgram.com/learn/how-to-add-speech-recognition-to-your-react-project)。 如果您想嘗試 API 來親自了解模型的靈活性,請查看他們的[API Playground](https://playground.deepgram.com/?smart_format=true&language=en&model=nova-2) 。 https://github.com/deepgram 明星 Deepgram ⭐️ --- 24. [OpenDevin](https://github.com/OpenDevin/OpenDevin) - 更少的程式碼,更多的內容。 ----------------------------------------------------------------------- ![奧彭文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4on63bb02g4x4ny8gtcn.png) ![奧彭文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0yepod2rye2jk5r12dt.png) 這是一個開源專案,旨在複製 Devin,一名自主人工智慧軟體工程師,能夠執行複雜的工程任務並在軟體開發專案上與用戶積極協作。該計畫致力於透過開源社群的力量複製、增強和創新 Devin。 只是想讓你知道,這是在德文被介紹之前。 您可以閱讀帶有要求的[安裝說明](https://github.com/OpenDevin/OpenDevin?tab=readme-ov-file#installation)。 他們使用 LiteLLM,因此您可以使用任何基礎模型來執行 OpenDevin,包括 OpenAI、Claude 和 Gemini。 如果您想為 OpenDevin 做出貢獻,您可以查看 [演示](https://github.com/OpenDevin/OpenDevin/blob/main/README.md#opendevin-code-less-make-more)和[貢獻指南](https://github.com/OpenDevin/OpenDevin/blob/main/CONTRIBUTING.md)。 它在 GitHub 上擁有超過 10,700 個 Star,並且正在快速成長。 https://github.com/OpenDevin/OpenDevin 明星 OpenDevin ⭐️ --- 25. [NPM Copilot](https://github.com/whoiskatrin/npm-copilot) - Next.js 的 CLI 工具,可以即時分析日誌。 ------------------------------------------------------------------------------------------ ![npm 副駕駛](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7omx4d2yzub3gx1xmkvh.png) npm/yarn/pnpm copilot 是一個命令列工具,它使用 OpenAI 的 GPT-3 語言模型來提供修復程式碼中錯誤的建議。 CLI 工具可偵測目前目錄中正在使用的專案類型和套件管理器。 然後,它執行適當的開發伺服器命令(例如,npm run dev、yarn run dev、pnpm run dev)並偵聽正在執行的應用程式產生的日誌。 當遇到錯誤時,CLI 工具會即時提供錯誤修復建議。 首先使用以下 npm 指令安裝 npm-copilot 套件。 ``` npm install -g npm-copilot ``` CLI 工具將開始監視 Next.js 應用程式產生的日誌,並即時提供錯誤修復建議。 您可以透過該命令在專案中使用它。 ``` npm-copilot ``` 他們在 GitHub 上有 338 顆星,支援`Next,js` 、 `React` 、 `Angular`和`Vue.js` https://github.com/whoiskatrin/npm-copilot 明星 NPM Copilot ⭐️ --- 26. [Mentat](https://github.com/AbanteAI/mentat) - 人工智慧編碼助理。 ------------------------------------------------------------ ![撒謊了](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yeba0cbns0fve53k5xk5.png) Mentat 是一款人工智慧工具,可直接從命令列幫助您完成任何編碼任務。 與 Copilot 不同,Mentat 協調多個位置和文件的編輯。與 ChatGPT 不同的是,Mentat 已經擁有您專案的上下文 - 無需複製和貼上! 您可以觀看此演示以了解基本概述。 https://www.youtube.com/watch?v=lODjaWclwpY 如果需要協助,您可以閱讀[安裝說明](https://github.com/AbanteAI/mentat?tab=readme-ov-file#install)或觀看安裝[教學](https://www.youtube.com/watch?v=bVJP8hY8uRM)。 您可以閱讀[文件](https://github.com/AbanteAI/mentat?tab=readme-ov-file#-usage)。 他們在 GitHub 上有 2.3k 顆星,並且正在發布`v1`版本。 https://github.com/AbanteAI/mentat Star Mentat ⭐️ --- 27. [FlowGPT](https://github.com/nilooy/flowgpt) - 使用 AI 產生流程圖。 --------------------------------------------------------------- ![流量GPT](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qzzpnc7doy4o6qizosjl.png) FlowGPT是一個用ai(gpt-3.5)產生流程圖的工具。 它是使用 Next.js、Langchain、Mermaid 和 DaisyUI 建構的。 您可以閱讀[安裝說明](https://github.com/nilooy/flowgpt?tab=readme-ov-file#installation)。 你可以查看[gif 示範](https://github.com/nilooy/flowgpt?tab=readme-ov-file#flowgpt-is-a-tool-to-generate-flowchart-with-ai-gpt-35)。 它只有 11 次提交,但在 GitHub 上有 238 顆星,並且是使用 TypeScript 建置的。作為一個小專案值得一試。 https://github.com/nilooy/flowgpt Star FlowGPT ⭐️ --- 28. [reor](https://github.com/reorproject/reor) - 自組織人工智慧筆記應用程式。 ---------------------------------------------------------------- ![我認為](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c0x2q2a67bg7gzdekizw.png) 迄今為止我見過的最令人興奮的專案之一,特別是因為它在本地執行模型。 Reor 是一款基於人工智慧的桌面筆記應用程式:它會自動連結相關筆記、回答筆記上的問題並提供語義搜尋。 所有內容都儲存在本地,您可以使用類似黑曜石的 Markdown 編輯器來編輯筆記。該專案假設人工智慧思維工具預設應該在本地執行模型。 Reor 站在 Ollama、Transformers.js 和 LanceDB 等巨頭的肩膀上,使 LLM 和嵌入模型都可以在本地執行。也支援連接到 OpenAI 或 OpenAI 相容 API(例如 Oobabooga)。 > 我知道你想知道它怎麼可能是`self-organizing` ? A。您寫的每個筆記都會被分塊並嵌入到內部向量資料庫中。 b.相關筆記透過向量相似度自動連接。 C。 LLM 支援的問答對筆記語料庫進行 RAG。 d.一切都可以進行語義搜尋。 您可以在這裡觀看演示! ![示範](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k1whpg9m7ubt5xluyf7f.gif) 將 Reor 視為一個帶有兩個生成器的 RAG 應用程式:LLM 和人類。在問答模式下,法學碩士會從語料庫中取得檢索到的上下文來幫助回答查詢。 類似地,在編輯器模式下,人們可以切換側邊欄以顯示從語料庫「檢索」的相關註釋。這是透過將當前筆記中的想法與語料庫中的相關想法交叉引用來「增強」您的想法的一種非常有效的方法。 您可以閱讀[文件](https://www.reorproject.org/docs)並從網站[下載](https://www.reorproject.org/)。 Mac、Linux 和 Windows 皆支援。 他們還提供了入門指南,以便幫助您入門。 ![入門指南](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bx3w7nalcwc9egumu0hm.png) 它們在 GitHub 上有 4.2k 顆星,並使用 TypeScript 建置。 https://github.com/reorproject/reor 星標 reor ⭐️ --- 29. [Amica](https://github.com/semperai/amica) - 讓您在瀏覽器中輕鬆地與 3D 角色聊天。 --------------------------------------------------------------------- ![朋友](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2nvizcn717h3cteocft5.png) Amica 是一個開源接口,用於透過語音合成和語音辨識與 3D 角色進行互動式通訊。 您可以匯入 VRM 文件,調整聲音以適合角色,並產生包含情緒表達的回應文字。 他們使用 Three.js、OpenAI、Whisper、Bakllava 等進行視覺處理。您可以閱讀[Amica 的工作原理](https://docs.heyamica.com/overview/how-amica-works)及其所涉及的[核心概念](https://docs.heyamica.com/overview/core-concepts)。 您可以克隆該存儲庫並使用它來[開始](https://docs.heyamica.com/getting-started/installation)。 ``` npm i npm run dev ``` 您可以閱讀[文件](https://docs.heyamica.com/)並查看[演示](https://amica.arbius.ai/),這真是太棒了:D ![示範](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/92iv9y2auly6tvenee82.png) 您可以觀看這段簡短的影片,了解它的功能。 https://www.youtube.com/watch?v=hUxAEnFiXH8 Amica 使用 Tauri 建立桌面應用程式。 他們在 GitHub 上有 400+ Stars,而且看起來非常容易使用。 https://github.com/semperai/amica Star Amica ⭐️ --- 30.[繼續](https://github.com/continuedev/continue)- 使您能夠建立人工智慧軟體開發系統。 ------------------------------------------------------------------- ![繼續](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ro5ctus5tdfvqdnysby.png) 繼續讓開發人員保持流動。我們的開源 VS Code 和 JetBrains 擴充功能可讓您輕鬆建立自己的模組化 AI 軟體開發系統並進行改進。 它們有很多很棒的功能,讓我們看看其中的一些: > 輕鬆理解程式碼部分。 ![程式碼部分](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lh8k3s0uv5y1assa50dl.gif) > 選項卡可自動完成程式碼建議。 ![自動完成](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/09xt6urla4jic5x3m5rr.gif) > 詢問有關您的程式碼庫的問題。 ![問題](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qd95frn0j9cd417yighz.gif) > 快速使用文件作為上下文。 ![文件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y2moxr84w6fwuwqvsccn.gif) > 立即了解終端錯誤。 ![錯誤](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kaaq6x5978tm1u61moxb.gif) > 使用斜槓指令開始操作。 ![命令](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j4vlzc2vuiuoivgqy5e7.png) > 重構您正在編碼的函數。 ![重構](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7wz1tzon8afivi79ulvn.png) 了解所有[功能](https://docs.continue.dev/how-to-use-continue)。 您必須從市場安裝[VSCode 擴展](https://marketplace.visualstudio.com/items?itemName=Continue.continue),然後閱讀[快速入門指南](https://docs.continue.dev/quickstart)。 您可以閱讀[文件](https://docs.continue.dev/intro)。 它們在 GitHub 上擁有超過 10k 顆星,並使用 TypeScript 建置。 https://github.com/continuedev/continue 星繼續 ⭐️ --- 我從來沒有如此詳細地介紹過這麼多專案! 我希望這能幫助您創造一些鼓舞人心的東西。 請分享更多專案或任何您想要其他人可以學習的內容! 請關注 Copilotkit 以獲取更多此類內容。 https://dev.to/copilotkit --- 原文出處:https://dev.to/copilotkit/30-ai-libraries-you-can-use-for-your-next-project-ideas-5ded

🌝 適合您下一個專案的 15 個 JavaScript 框架 ⚔

開發者生態系統已經發展了很多,並且有許多開發者不知道的框架。 我們「作為開發人員」有很多關於如何建立我們的應用程式的框架選項。這些選擇非常重要。 讓我們介紹 15 個框架,供您製作下一個專案。我將提供詳細的資源,以便您可以學習其中的每一個。 相信我!這份清單就是您所需要的。 讓我們開始吧。 ![下一級](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ychbi440selxu1ftf5n8.gif) --- ### 庫與框架 在開始之前,讓我們先來了解一下框架與函式庫有何不同。開發人員可以互換使用它! 函式庫和框架都是由其他人編寫的可重複使用程式碼。 > 簡單來說: 將圖書館想像成IKEA之旅。您家裡有自己的空間,但您需要一些家具幫助。您不想從頭開始,所以您可以前往宜家,在那裡您可以挑選您需要的東西。你是做出決定的人。 現在,框架更像是建造一個樣品房。您已經有了一套計劃以及一些佈局和設計的選擇。但最終,藍圖和建造者處於控制之中。他們會讓你知道在哪裡可以加入你的意見,但他們正在掌控一切。 > 從技術角度來說。 透過庫,您可以指導應用程式的流程。您決定何時何地使用庫的功能。但有了框架,框架就控制了流程。它為您提供了一些插入程式碼的位置,但它是程式碼執行時發號施令的地方。 我使用了 Freecodecamp 的這篇文章“ [框架和庫之間的區別](https://www.freecodecamp.org/news/the-difference-between-a-framework-and-a-library-bd133054023f/)”,特別是因為它的解釋很簡單。完整閱讀一下! --- 1. [Wing](https://git.new/winlang-repo) - 一種雲端程式語言。 --------------------------------------------------- ![翅膀](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n97bowkrexjk46n94bcc.png) Wing是一個旨在開發雲端應用程式的框架。 它允許您在雲端中建立應用程式,並且具有相當簡單的語法。 核心概念是您可以直接在應用程式中指定資源。 您可以執行本機模擬並使用 Winglang 控制台視覺化每個步驟中發生的情況。 ![機翼基礎設施](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eun3zd1gkp870rj57eeu.png) 你**程式碼**。**本地測試**。**編譯**。**部署到雲端提供者**。 Wing 需要 Node `v20 or higher` 。 建立一個父目錄(我們使用的是`shared-counter` )並使用 Vite 使用新的 React 應用程式設定前端。您可以使用這個 npm 指令。 ``` npm create -y vite frontend --template react-ts // once installed, you can check if it's running properly. cd frontend npm install npm run dev ``` 您可以使用此 npm 命令安裝 Wing。 ``` npm install -g winglang ``` 您可以使用`wing -V`驗證安裝。 Wing 還提供官方[VSCode 擴充功能](https://marketplace.visualstudio.com/items?itemName=Monada.vscode-wing)和[IntelliJ](https://plugins.jetbrains.com/plugin/22353-wing) ,後者提供語法突出顯示、補全、轉到定義和嵌入式 Wing 控制台支援。您可以在建立應用程式之前安裝它! 您可以使用 Wing 作為雲端後端來建立任何全端應用程式。 建立後端目錄。 ``` mkdir ~/shared-counter/backend cd ~/shared-counter/backend ``` 建立一個新的空 Wing 專案。 ``` wing new empty // This will generate three files: package.json, package-lock.json and main.w file with a simple "hello world" program wing it // to run it in the Wing simulator // The Wing Simulator will be opened in your browser and will show a map of your app with a single function. //You can invoke the function from the interaction panel and check out the result. ``` 使用指令`wing new empty`後的結構如下。 ``` bring cloud; // define a queue, a bucket, and a counter let bucket = new cloud.Bucket(); let counter = new cloud.Counter(initial: 1); let queue = new cloud.Queue(); // When a message is received in the queue -> it should be consumed // by the following closure queue.setConsumer(inflight (message: str) => { // Increment the distributed counter, the index variable will // store the value before the increment let index = counter.inc(); // Once two messages are pushed to the queue, e.g. "Wing" and "Queue". // Two files will be created: // - wing-1.txt with "Hello Wing" // - wing-2.txt with "Hello Queue" bucket.put("wing-{index}.txt", "Hello, {message}"); log("file wing-{index}.txt created"); }); ``` 您可以安裝`@winglibs/vite`來啟動開發伺服器,而不是使用`npm run dev`來啟動本機 Web 伺服器。 ``` // in the backend directory npm i @winglibs/vite ``` 您可以使用`backend/main.w`中提供的 publicEnv 將資料傳送到前端。 讓我們來看一個小例子。 ``` // backend/main.w bring vite; new vite.Vite( root: "../frontend", publicEnv: { TITLE: "Wing + Vite + React" } ); // import it in frontend // frontend/src/App.tsx import "../.winglibs/wing-env.d.ts" //You can access that value like this. <h1>{window.wing.env.TITLE}</h1> ``` 你還可以做更多: - 讀取/更新 API 路線並使用 Wing Simulator 檢查它。 - 使用後端獲取值。 - 使用`@winglibs/websockets`來同步瀏覽器,在後端部署一個 WebSocket 伺服器,你可以連接這個 WebSocket 來接收即時通知。 可以節省大量時間的一些功能包括熱重載,以獲得即時回饋並順利產生必要的安全策略。 無需學習每個雲端提供者的語法。 您的程式碼可以編譯到 AWS、GCP、Azure 或任何自訂平台。太棒了:D 您可以閱讀完整的逐步指南,以了解[如何使用 React 作為前端和 Wing 作為後端建立簡單的 Web 應用程式](https://www.winglang.io/docs/guides/react-vite-websockets)。測試是使用 Wing Simulator 完成的,並使用 Terraform 部署到 AWS。 部署後的AWS架構是這樣的。 ![建築學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/27awil840ktgh3jvklij.png) 為了提供開發者選擇和更好的體驗,Wing 推出了對[TypeScript (Wing)](https://www.winglang.io/docs/typescript/)等其他語言的全面支援。唯一強制的事情是您必須安裝 Wing SDK。 這也將使控制台完全可用於本地偵錯和測試,而無需學習 Wing 語言。 該翼目前支援以下輸出: - AWS CDK 平台 - Terraform/AWS 平台 - Terraform/GCP 平台 - Terraform/Azure 平台 - 模擬器平台 - 客製化平台 Wing 甚至還有其他[指南](https://www.winglang.io/docs/category/guides),因此更容易遵循。 ![指南](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/31czxehkg10ezmlpf7ac.png) 您可以閱讀[文件](https://www.winglang.io/docs)並查看[範例](https://www.winglang.io/docs/category/examples)。 您也可以在[Playground](https://www.winglang.io/play/)中使用 Wing 查看結構和範例。 如果你比較像輔導員。看這個! {% 嵌入 https://www.youtube.com/watch?v=wzqCXrsKWbo %} ![機翼工作流程](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l8zqja0w9kyoibrskjmp.gif) Wing 在 GitHub 上有 4500+ 顆星,1600+ 個版本,但仍未進入 v1 版本,這意味著意義重大。 {% cta https://git.new/winlang-repo %} 星翼 ⭐️ {% endcta %} --- 2. [Nest](https://github.com/nestjs/nest) - 高效且可擴展的伺服器端應用程式。 ------------------------------------------------------------ ![巢](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/inlcpt901r5kiwm4eeor.png) 一個先進的 Node.js 框架,用於使用 TypeScript/JavaScript 建立高效且可擴展的伺服器端應用程式。 它使用現代 JavaScript,使用 TypeScript 建構(保留與純 JavaScript 的兼容性),並結合了 OOP(物件導向程式設計)、FP(函數式程式設計)和 FRP(函數式反應式程式設計)的元素。 在底層,Nest 使用 Express,但也提供與 Fastify 等各種其他庫的兼容性,從而可以輕鬆使用無數可用的第三方外掛程式。 Nest 提供了高於這些常見 Node.js 框架(Express/Fastify)的抽象級別,但也直接向開發人員公開其 API。這為開發人員提供了一定程度的自由。 在我們了解更多之前,請觀看 100 秒內的 Nestjs! {% 嵌入 https://www.youtube.com/watch?v=0M8AYU\_hPas&amp;pp=ygUXZW1iZXIganMgaW4gMTAwIHNlY29uZHM%3D %} 考慮到它們提供的靈活性,您當然不必重新發明輪子。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6h6yjfmq1h5qn5765by0.png) 這是使用 Nest CLI 設定新專案的方法。 ``` npm i -g @nestjs/cli nest new project-name ``` 這將引導該應用程式。 ``` import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap(); ``` 您可以閱讀[文件](docs.nestjs.com)。 他們還提供一套付費課程(我想知道為什麼)。如果您需要完整的路線圖並想成為 Nest 的使用專家,請隨時查看它們。 但我建議使用 Freecodecamp 提供的這些免費教學來學習。 - [NestJs 初學者課程 - 建立 REST API](https://www.youtube.com/watch?v=GHTA143_b-s) - 大約 3.42 小時,涵蓋許多[主題](https://www.freecodecamp.org/news/learn-nestjs-by-building-a-crud-api/)。 - [綜合 NestJS 課程](https://www.youtube.com/watch?v=sFnAHC9lLaw&t=1s)- 涵蓋 20 個模組,時長 14 小時。 {% 嵌入 https://www.youtube.com/watch?v=sFnAHC9lLaw&amp;t=1s %} 如果您正在尋找入門專案,請學習[如何在 NestJS 中使用 Nodemailer 發送電子郵件](https://www.freecodecamp.org/news/how-to-use-nodemailer-in-nestjs/)。您可以使用它來獲得紮實的基礎知識。 Nest.js 擁有龐大的開發人員社區,並被許多公司使用。尋找已使用 Nest[的專案和公司的完整清單](https://docs.nestjs.com/discover/companies)。 ![公司](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ic0z3dts7bmw5s3e5gmf.png) 順便說一句,作為初學者,我最常擔心的是相似的名稱:Nextjs、Nuxtjs 和 Nestjs。我涵蓋了所有內容,這樣您就不必感到困惑。哈哈! Nest 在 GitHub 上擁有超過 64k 個 star,提交次數超過 15k,並且已發布`v10`版本。 {% cta https://github.com/nestjs/nest %} 星巢 ⭐️ {% endcta %} --- 3. [Gatsby](https://github.com/gatsbyjs/gatsby) - 最好的基於 React 的框架,具有內建的效能、可擴展性和安全性。 ----------------------------------------------------------------------------------- ![蓋茲比](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0drinpwldeyfxd82lgf.png) Gatsby 是一個基於 React 的免費開源框架,可協助開發人員建立速度極快的網站和應用程式。 它將動態呈現網站的控制和可擴展性與靜態網站生成的速度結合起來,創造了一個全新的可能性網絡。 Gatsby 從任何資料來源提取資料,無論是 Markdown 檔案、Contentful 或 WordPress 等無頭 CMS,還是 REST 或 GraphQL API。使用來源插件載入資料,然後使用 Gatsby 的統一 GraphQL 介面進行開發。 與 Next.js 不同,Gatsby 不執行伺服器端渲染。相反,它會在建置期間在客戶端產生 HTML 內容。 我見過一些使用 Gatsby 建立的優秀作品集。 開始使用以下 npm 指令。 ``` npm init gatsby ``` 它會要求提供網站標題和專案目錄的名稱。繼續按照提示選擇您的首選語言(JavaScript 或 TypeScript)、CMS、樣式工具和其他功能。 您可以這樣使用它。 ``` cd my-gatsby-site // to start the local dev server npm run develop ``` 您可以閱讀[文件](https://www.gatsbyjs.com/docs)。我個人很喜歡文件的流程。 您也可以按照[教學](https://www.gatsbyjs.com/docs/tutorial/getting-started/)開始,[操作指南](https://www.gatsbyjs.com/docs/how-to/)和[概念指南](https://www.gatsbyjs.com/docs/conceptual/)深入了解 Gatsby 概念以及網站架構。 Gatsby 提供了開箱即用的 PWA 和大量主題。使用 Gatsby 主題,您的所有預設配置(共享功能、資料來源、設計)都會從您的網站中抽象化出來,並放入可安裝的套件中。您可以閱讀有關[主題的](https://www.gatsbyjs.com/docs/themes/)更多資訊。 例如, `gatsby-theme-blog`是用於建立部落格的官方 Gatsby 主題。可能有可以透過`gatsby-config.js`配置的主題選項。 ``` npm install gatsby-theme-blog ``` 對於電子商務商店或廣泛的媒體網站等內容密集的企業級網站來說,Gatsby 並不是理想的解決方案。隨著內容大小的增加,建置時間將急劇增加。 尋找使用 Gatsby 建立的[606 個網站](https://www.gatsbyjs.com/showcase/)的清單。其中,53 個網站是開源的,因此這可以提供靈感,也是一個起點。 ![展示](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/439taxdhursvmjwhcxgc.png) 他們還提供了[大量按類別劃分的插件](https://www.gatsbyjs.com/plugins)以及每個插件中清晰的文件。其中一個範例是將 Google Analytics 新增至您的應用程式的插件。 ``` npm install gatsby-plugin-google-analytics ``` ![外掛](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rwq1dsyfdqdkmfetebj9.png) 您也可以使用 Gatsby 的[Starter 庫](https://www.gatsbyjs.com/starters/)。使用 Gatsby 建立下一個應用程式還需要什麼? ![入門庫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u831zo26ttg6tvzu6shq.png) 使用這些[參考指南](https://www.gatsbyjs.com/docs/reference/)來獲取有關 Gatsby API 的詳細資訊。 如果您喜歡完整的課程,我建議您觀看[Gatsby 靜態網站產生器教學](https://www.youtube.com/watch?v=RaTpreA0v7Q)- Freecodecamp 提供的 9 小時教學。 Gatsby 在 GitHub 上有 55,000 顆星,目前處於 v5 版本,並有超過 245,000 名開發人員使用。 {% cta https://github.com/gatsbyjs/gatsby %} 明星蓋茲比 ⭐️ {% endcta %} --- 4. [Nextjs](https://github.com/vercel/next.js) - Web 的 React 框架。 ---------------------------------------------------------------- ![下一個js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/da26rscfzozpe307xz2g.png) 由於它提供的優化級別,它是我最喜歡的框架之一。 Next.js 使您能夠透過擴展最新的 React 功能並整合強大的基於 Rust 的 JavaScript 工具來建立全端 Web 應用程式,以實現最快的建置。 Next.js 由荷蘭公司 Vercel(以前稱為 ZEIT)於 2017 年建立。 Next.js 也像 Gatsby 一樣提供靜態產生器。 Next.js 的建置遵循`Build once, runs everywhere`的原則,因此您可以使用 Next.js 製作 Web 應用程式、行動應用程式、桌面應用程式和漸進式 Web 應用程式。 ![下一個js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4j16td403jbbyyk7xz2v.png) Nextjs 提供了許多功能,例如檔案路由、渲染技術(例如 ISR)以及深層的圖像和字體最佳化。你可以檢查任何 nextjs 網站的 SEO 統計資料,在大多數情況下它都是一流的。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zr9yx5n6gy2q764gak8x.png) ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5mf9r3zohetcsyatp90z.png) 開始使用以下 npm 指令。 ``` npx create-next-app@latest ``` 您可以閱讀[文件](https://nextjs.org/docs)並按照[本指南](https://nextjs.org/docs/getting-started/installation)開始使用。 其中涉及很多概念,閱讀完整的文件需要幾個月的時間。我前段時間寫過一篇文章,你可以看看。它並沒有出名,但它是我憑藉多年的 Nextjs 經驗編寫的最好的文章之一。我還提到了 Nextjs 團隊提供的[官方課程](https://nextjs.org/learn/dashboard-app/getting-started)。 {% 嵌入 https://dev.to/anmolbaranwal/12-things-you-didnt-know-you-could-do-with-nextjs-386b %} 如果您想透過 YouTube 教學進行學習,我建議您觀看這些最近的教程,因為文件更新得非常頻繁,因此最好觀看最近的內容,而不是幾年前的內容。 - \[帶有 TypeScript 的 Nextjs 13(應用程式路由器)\](https://www.youtube.com/watch?v=ZVnjOPwW4ZA&amp;pp=ygUTbmV4dGpzIGNyYXNoIGNvdXJzZQ%3D%3D ) - 1 小時教程。 - [Next.js 14 完整課程 2024](https://www.youtube.com/watch?v=wm5gMKuwSYk) - 3 小時教學。 您也可以觀看 Nextjs 100 秒。他們加入了一個基本教程,使其長達 11 分鐘。 {% 嵌入 https://www.youtube.com/watch?v=Sklc\_fQBmcs&amp;t=4s&amp;pp=ygUObmV4dGpzIGluIDEwMHM%3D %} 我自己使用文件學習了它,並使用它建置了超過 6 個專案,甚至是一個超過 20k 程式碼庫的 SAAS 應用程式。這就是為什麼我說,它是您可以選擇的最佳框架之一。 使用 Next.js 建立的一些熱門網站包括 Auth0、Coinbase、Docker、GitHub、Hulu、Netflix、Sesame、Starbucks、Trulia、Twitch 和 Uber。你可以看到所有使用Nextjs的[網站](https://nextjs.org/showcase)。 ![下一個js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iafbez4aptnb7f0iqtgz.png) 他們還提供了各種可以直接使用的[入門模板](https://vercel.com/templates/next.js)。 ![入門模板](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1egye2mtz7f3ehzsm9ja.png) ![電子商務](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d4ge39gpt0xo3rtvn1i5.png) Next 在 GitHub 上有 12 萬顆星,發布`v14.2`版本,在 NPM 上每週下載量超過 600 萬次。如其儲存庫所示,有 260 萬開發人員使用。 {% cta https://github.com/vercel/next.js %} 明星 Nextjs ⭐️ {% endcta %} --- 5. [Preact](https://github.com/preactjs/preact) - 具有相同現代 API 的快速 3kB React 替代品。 ------------------------------------------------------------------------------- ![預反應](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/npzj10prb5i8noahsops.png) Preact 是一個輕量級、快速、高效能的函式庫,是 React 的替代品。 Preact 的大小僅為 3kb(經過壓縮和壓縮),但卻為您提供了 React 所需的所有功能,使其成為最好的 JavaScript 框架之一。 Preact 的建立者 Jason Miller 是 Google 的高級開發者計畫工程師。 Preact 基本上具有 Virtual DOM 元件的所有功能,而沒有諸如以下的開銷: - 熟悉 React API 和 ES6 類別、鉤子和功能元件模式。 - 透過簡單的 preact/compat 別名實現廣泛的 React 相容性。 - 您需要的一切,例如 JSX、VDOM、DevTools、HMR、SSR。 在生產過程中,您可以輕鬆地從現有專案中的 React 切換到 Preact,因為它們支援相同的 API。 程式碼範例結構如下所示。您也可以查看此範例[程式碼筆](https://codepen.io/developit/pen/LpNOdm),您可以查看它以了解 Preact 中程式碼庫的結構。 ![程式碼結構](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n3mwphw4vjfm1a3cquyv.png) 開始使用以下 npm 指令。 ``` npm init preact ``` 這是執行開發伺服器的方式。 ``` # Go into the generated project folder cd my-preact-app # Start a development server npm run dev ``` 您將必須配置一些東西,尤其是別名。請遵循[本指南](https://preactjs.com/guide/v10/getting-started)。 您可以閱讀[文件](https://preactjs.com/guide/v10/getting-started/)並查看詳細的[演示和範例](https://preactjs.com/about/demos-examples)清單。 他們還提供了基於 Web 的[教程](https://preactjs.com/tutorial/),您可以按照該教程來學習 Preact。 如果您需要範例應用程式、樣板檔案、元件、工具包等,請使用[Awesome Preact](https://github.com/preactjs/awesome-preact) 。 Preact 在 GitHub 上有 36,000 顆星,目前已發布`v10`版本。 {% cta https://github.com/preactjs/preact %} Star Preact ⭐️ {% endcta %} --- 6. [tRPC](https://github.com/trpc/trpc) - 端到端類型安全性 API 變得簡單。 ------------------------------------------------------------ ![特爾普克](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ck7ve1epya6ofshzmc2c.png) tRPC 可讓您輕鬆建立和使用完全類型安全的 API,而無需模式或程式碼產生。 ![gif 動態圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2bssocrvw9pt0y1lnunk.gif) 上面的客戶端沒有從伺服器導入任何程式碼,僅導入其類型聲明 如果我們要深入了解,那麼您絕對應該閱讀一些歷史。 {% 嵌入 https://dev.to/zenstack/a-brief-history-of-api-rpc-rest-graphql-trpc-fme %} 目前,GraphQL 是在 TypeScript 中實作型別安全 API 的主要方式(這太棒了!)。由於 GraphQL 被設計為用於實現 API 的與語言無關的規範,因此它沒有充分利用 TypeScript 這樣的語言的強大功能。 如果您的專案是使用全端 TypeScript 建置的,您可以直接在客戶端和伺服器之間共用類型,而無需依賴程式碼生成。 tRPC 適用於全端 TypeScript 開發人員。它使您可以輕鬆編寫可以在應用程式的前端和後端安全使用的端點。 API 合約的類型錯誤將在建置時被捕獲,從而減少應用程式在執行時出現錯誤的可能性。 這是為 Mono 儲存庫設計的,因為您需要從伺服器匯出/匯入類型定義。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6v56rl2jkgfat6xsf909.png) 開始使用以下 npm 指令。 ``` npm install @trpc/server@next @trpc/client@next ``` 您必須使用實例定義後端路由器。閱讀[快速入門指南](https://trpc.io/docs/quickstart)以了解更多詳細資訊。 了解[trpc 中涉及的概念](https://trpc.io/docs/concepts)(例如 rpc 和使用的術語)非常重要。 您可以閱讀[文件](https://trpc.io/docs)。 如果您已經在一個混合語言的團隊中工作,或者擁有您無法控制的第三方消費者,那麼您應該建立一個與語言無關的 GraphQL-API。 如果您想測試一下,我建議使用此[模板](https://github.com/new?template_name=examples-minimal&template_owner=trpc),其中包含一個最小的範例。 您還可以觀看這個[45 分鐘的 YouTube 教學](https://www.youtube.com/watch?v=UfUbBWIFdJs&pp=ygUMd2hhdCBpcyB0cnBj)來了解有關 trpc 的更多資訊。 {% 嵌入 https://www.youtube.com/watch?v=UfUbBWIFdJs&amp;pp=ygUMd2hhdCBpcyB0cnBj %} 它們在 GitHub 上擁有超過 32,000 顆星,目前處於`v11` beta 版本,並被 51,000 名開發人員使用。 {% cta https://github.com/trpc/trpc %} 啟動 tRPC ⭐️ {% endcta %} --- [7.Nuxtjs](https://github.com/nuxt/nuxt) - 直覺的 Vue 框架。 ------------------------------------------------------ ![努克斯特](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ct9usemwuhvtrjcx0na8.png) Nuxt 是一個基於 Vue.js 生態系統的漸進式開源框架,用於建立高效能 Web 應用程式,尤其是伺服器端渲染應用程式。 但請記住,Nuxt 並不是 Vue.js 的替代品,因為它無法單獨運作。而且它也不能被視為像 Express 這樣成熟的後端框架。 100 秒觀看 Nuxtjs,掌握整體概念。 {% 嵌入 https://www.youtube.com/watch?v=dCxSsr5xuL8 %} Nuxt 是建立這三種 Web 應用程式的最佳 JavaScript 框架之一 - 預先渲染靜態頁面、單頁 Web 應用程式 (SPA)、伺服器端渲染 Web 應用程式 (SSR) 甚至通用應用程式。 開發人員特別喜歡 Nuxt,因為它有豐富的函式庫和模組。 ![組合特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kknguo9v9dnqu2npfp68.png) 開始使用以下 npm 指令。 ``` npx nuxi@latest init <my-project> ``` 您可以閱讀[文件](https://nuxt.com/docs/getting-started/introduction)並檢查[codesandbox範例](https://codesandbox.io/s/github/nuxt/starter/tree/v3/)。 您可以按照本[指南](https://nuxt.com/docs/guide/concepts/auto-imports)了解更多關鍵概念。 有許多整合選項,因此您可以更輕鬆地繼續使用您喜歡的工具和服務。 ![整合選項](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/irikkgro0cp4l8svioi9.png) 您可以查看[免費課程清單](https://nuxt.com/video-courses)來了解 Nuxt 生態系統。 如果您想要推薦的課程,請學習[Nuxt 3 — 初學者課程](https://www.youtube.com/watch?v=fTPCKnZZ2dk)— Freecodecamp 提供的 3 小時教學。 使用 Nuxt 建立的一些流行網站包括 Aircall、Amplitude、Backmarket、Bitpay、Bootstrap Vue、Fox News、Gitlab、Icons8、Instrument、MyScript、Nespresso、Note.com、Ozon.ru、Roland Garros、System76、Todoist、加油,Wappalyzer 。尋找不同類別下[展示網站的完整清單](https://nuxt.com/showcase)。 如果您想快速測試和建置,那麼我建議您查看[入門模板](https://nuxt.com/templates)。 ![範本](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bn61xrcx9ym3a40kewwf.png) Nuxt 在 GitHub 上擁有超過 51,000 顆星,並被超過 318,000 名開發者使用。 {% cta https://github.com/nuxt/nuxt %} Star Nuxt ⭐️ {% endcta %} --- 8. [Ember.js](https://github.com/emberjs/ember.js) - 用於建立雄心勃勃的 Web 應用程式的 JavaScript 框架。 --------------------------------------------------------------------------------------- ![man.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z8ygtjex9ve6e2gbsfh0.png) Ember.js 是一個 JavaScript 框架,用於為企業建立可擴展的單頁 Web 應用程式。與其他框架不同,模型-視圖-視圖模型 (MVVW) 架構是 Ember 的基礎。 Ember.js 最初是一個 SproutCore 2.0 框架,由其建立者 Yehuda Katz 更名為 Ember.js,Yehuda Katz 是一位出色的開發人員,被譽為 jQuery 的主要建立者之一。 他們還提供命令列介面工具。 Ember CLI 是建立、建置、測試和提供構成 Ember 應用程式或外掛程式的檔案的官方方式。 ``` npm install -g ember-cli ``` 儘管與 React、Vue 和 Svelte 相比,Ember.js 是一個較舊的前端 JavaScript 框架,但它仍然具有強大的功能,並且在 Microsoft、LinkedIn、Netflix 和 Twitch 等大公司中擁有龐大的用戶群。查看[完整清單](https://emberjs.com/ember-users/)。 ![使用 ember.js 的公司](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0w87sxixh8js9luyv7jc.png) 借助強大的預設設置,您可能永遠不需要在應用程式中配置任何內容,但如果您需要的話,選項就在那裡! 這意味著 Ember.js 遵循「CoC – 約定優於配置」方法,這可確保在大多數情況下不需要任何配置,以便您可以直接跳到編碼和建立 Web 應用程式。 它們還支援類似於 AngularJS 的 2 路資料綁定。 當我們深入研究時,了解 ember.js 是如何誕生的、其建立背後的先驅者以及製作開源軟體時做出的改變生活的決定非常重要。看這個! {% 嵌入 https://www.youtube.com/watch?v=Cvz-9ccflKQ %} 安裝 Ember CLI 後。 ``` npm install -g ember-cli ``` 您可以建立一個新應用程式,如圖所示。 ``` ember new ember-quickstart --lang en cd ember-quickstart npm start ``` 您可以閱讀[詳細的快速入門文件](https://guides.emberjs.com/release/getting-started/quick-start/)和[官方指南](https://guides.emberjs.com/release/)。 要學習 ember.js,您可以按照他們的官方團隊建立的[逐步教程](https://guides.emberjs.com/release/tutorial/part-1/)進行操作。您可以在[Ember API 文件](https://api.emberjs.com/ember/release)上閱讀有關 API 的更多資訊。 有數以千計的 JavaScript 庫可以在 Ember 中很好地工作。當 npm 套件提供一些 Ember 特定的功能時,他們稱之為`addon` 。外掛程式提供了一種編寫可重複使用程式碼、共用元件和樣式、擴充建置工具等的方法,所有這些都只需最少的配置。尋找[插件的完整清單](https://emberobserver.com/)。 ![外掛](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wlrw4m6u46fijp7kt7ky.png) 如果您正在尋找更多文章來學習 Ember.js,我推薦這些: - [Ember JS Essentials:Startech 提供的安裝及其功能的初學者指南](https://www.startechup.com/blog/ember-js/)。 - Toptal [建立您的第一個 Ember.js 應用程式的指南](https://www.toptal.com/javascript/a-step-by-step-guide-to-building-your-first-ember-js-app)。 這足以理解結構並決定 Ember 何時適合您的專案。 他們在 GitHub 上有 22k+ 顆星,而`v5.8`版本有 500 多個版本。 {% cta https://github.com/emberjs/ember.js %} 明星 Ember.js ⭐️ {% endcta %} --- 9. [Backbone.js](https://github.com/jashkenas/backbone) - 為您的 JS 應用程式提供一些帶有模型、視圖、集合和事件的 Backbone。 ------------------------------------------------------------------------------------------------- ![骨幹](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qysm5n76o7wdf1u48bii.png) Backbone.js 是一個基於 JavaScript 的框架,透過 RESTful JSON 介面連接到 API。 Jeremy Ashkenas 因建立一些最好的 JavaScript 框架(例如 CoffeeScript 和 Underscore.js)而聞名,他於 2010 年 10 月推出了 Backbone.js。 它旨在建立單頁 Web 應用程式並維護不同 Web 應用程式元件(例如眾多客戶端和伺服器)之間的同步。 Backbone.js 以小而輕而聞名,因為它只需要 jQuery 和一個 JavaScript 函式庫 Underscore.js 即可使用整個函式庫。 Backbone.js 透過提供具有鍵值綁定和自訂事件的模型、具有豐富的可枚舉函數API 的集合、具有聲明性事件處理的視圖,為JavaScript 密集型應用程式提供結構,並透過RESTful JSON 接口將其全部連接到您現有的應用程式。 這是一個簡單的主幹視圖。 ``` var AppView = Backbone.View.extend({ // el - stands for element. Every view has an element associated with HTML // content will be rendered. el: '#container', // It's the first function called when this view is instantiated. initialize: function(){ this.render(); }, // $el - it's a cached jQuery object (el), in which you can use jQuery functions // to push content. Like the Hello World in this case. render: function(){ this.$el.html("Hello World"); } }); ``` 您可以閱讀[文件](https://backbonejs.org/)。 Backbone.js 被許多值得信賴的公司使用,例如 Walmart、Pinterest、SoundCloud 等。 您可以參考他們的[wiki](https://github.com/jashkenas/backbone/wiki/Tutorials%2C-blog-posts-and-example-sites) ,其中記錄了教程、部落格文章和範例網站。 您可以參考幾篇很棒的文章來了解更多: - [BackboneJS:入門](https://auth0.com/blog/backbonejs-getting-started/)- 推薦。 - [適合絕對初學者的 Backbone.js](https://adrianmejia.com/backbone-dot-js-for-absolute-beginners-getting-started/) - [BackboneJS 教學](https://www.tutorialspoint.com/backbonejs/index.htm)- 教學點。 根據儲存庫統計,它們在 GitHub 上擁有超過 28,000 顆星,並被超過 66,000 名開發人員使用。 {% cta https://github.com/jashkenas/backbone %} 明星 Backbone.js ⭐️ {% endcta %} --- 10. [Svelte](https://github.com/sveltejs/svelte) - 控制論增強的網路應用程式。 ---------------------------------------------------------------- ![苗條的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r8xe2ni4di3g5qr03woh.png) Svelte 是一種建立 Web 應用程式的新方法。 它是由 Rich Harris(著名前端開發人員)建立的。 Svelte 於 2016 年首次推出,人氣暴漲。 許多開發人員認為 Svelte 是一個真正改變遊戲規則的革命性想法,它從根本上改變了我們編碼 Web 應用程式的方式。 與 React 或 Vue.js 等其他 JavaScript 框架不同,Svelte 沒有虛擬 DOM。相反,您可以使用簡單的 HTML、CSS 和 JavaScript 程式碼來建立無樣板的元件。 然後,Svelte Compiler 在建置期間將此程式碼編譯成小型的無框架的普通 JavaScript 模組,並在狀態變更時精確地更新 DOM。 因此,與 React 或 Vue.js 等其他傳統框架不同,Svelte 不需要很高的瀏覽器處理能力。 Svelte 依靠反應式程式來徹底更新 DOM。因此,與幾乎任何其他框架相比,它可以實現最快的渲染,並且在大多數效能基準測試中名列前茅。 開始使用以下 npm 指令。 ``` npm create svelte@latest my-app ``` 您可以這樣使用它。 ``` cd my-app npm install npm run dev -- --open ``` 您可以閱讀[文件](https://svelte.dev/docs/introduction)。該團隊還提供了[官方的 VSCode 擴展](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode),它也可以與各種其他編輯器和工具整合。 ![苗條的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/322jqc224gf3efcifmjs.png) 他們還提供了[詳細的基於網路的教程](https://svelte.dev/tutorial/basics)來學習 Svelte。 您可以查看所有[範例](https://svelte.dev/examples/nested-components)來了解關鍵概念和結構,包括 DOM 事件、生命週期、運動、過渡和處理 SVG。 ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4vfwmw0q3p68byme0b4c.png) 您可以觀看這些教學來了解有關 Svelte 的所有知識。 - [Learn Svelte – 初學者完整課程](https://www.youtube.com/watch?v=UGBJHYpHPvA)– Freecodecamp 的 23 小時教學。 - [Sveltekit &amp; Tailwind](https://www.youtube.com/watch?v=vb7CgDcA_6U&t=2s) - Freecodecamp 的 2 小時教學。 非常感謝老師們免費提供如此詳細的教學! Svelte 在 GitHub 上擁有超過 76k 顆星,目前處於`v4.2`版本,有 282k 開發人員使用。 {% cta https://github.com/sveltejs/svelte %} Star Svelte ⭐️ {% endcta %} --- 11. [Remix](https://github.com/remix-run/remix) - 建立更好的網站。 ---------------------------------------------------------- ![混音](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/en7mvytauu0b7pkm04df.png) Remix 是一個全端Web 框架,可讓您專注於使用者介面並透過Web 基礎知識進行工作,以提供快速、流暢且有彈性的使用者體驗,可部署到任何Node.js 伺服器,甚至非Node. js 環境像 Cloudflare Workers 這樣的邊緣。 Remix 建構在 React Router 之上,有四個特點: - 一個編譯器 - 伺服器端 HTTP 處理程序 - 一個伺服器框架 - 一個瀏覽器框架 您可以觀看此內容以了解有關 Remix by Fireship 的更多資訊。 {% 嵌入 https://www.youtube.com/watch?v=r4B69HAOXnA&amp;pp=ygUUcmVtaXggaW4gMTAwIHNlY29uZHM%3D %} 透過嵌套路由,Remix 可以消除幾乎所有載入狀態,如圖所示。 ![混音](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wyr8c9opmrn4chvr88jz.png) 開始使用以下 npm 指令。 ``` npx create-remix@latest ``` 您可以這樣使用它。 ``` mkdir my-remix-app cd my-remix-app npm init -y # install runtime dependencies npm i @remix-run/node @remix-run/react @remix-run/serve isbot@4 react react-dom # install dev dependencies npm i -D @remix-run/dev vite ``` 如果您想包含您的伺服器,請閱讀此[快速入門指南](https://remix.run/docs/en/main/start/quickstart),並了解更多有關如何透過 Remix Vite 插件提供 Vite 配置的訊息,因為 Remix 使用 Vite。 您可以閱讀[文件](https://remix.run/docs/en/main)。他們根據你想做的事情來分發它,順便說一句,我很喜歡。 ![文件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ljjae4pcyukr1j4nnweo.png) 尋找使用 Remix 建立的[網站的完整清單](https://remix.run/showcase)。 ![混音](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qjzhuy4njph0gckemdq5.png) 您還應該查看社區製作的[Remix 資源](https://remix.run/resources?category=all)。其中一些是有幫助的,可以改善整個生態系統。 ![生態系統](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9q5hdc59czs31nkbyhqq.png) 如果您是第一次接觸 Remix,我建議您閱讀官方團隊建立的[Remix 教學 -30min](https://remix.run/docs/en/main/start/tutorial) 。 他們在 GitHub 上擁有超過 27k 個 star,並且發布了`v2.8`版本。 {% cta https://github.com/remix-run/remix %} 明星混音 ⭐️ {% endcta %} --- 12. [AdonisJS](https://github.com/adonisjs/core) - TypeScript 優先的 Web 框架,用於建立 Web 應用程式和 API 伺服器。 ------------------------------------------------------------------------------------------------ ![阿多尼斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k8ishs5q78nu1yc3qrl4.png) AdonisJS 是一個功能齊全的 Node.js 後端框架。該框架是從頭開始建立的,非常重視開發人員的人體工學和易用性。 AdonisJS 專注於後端,讓您選擇您選擇的前端堆疊,這意味著前端不可知。 它是 Node.js 社群中最稀有的框架之一,附帶一套第一方包,可幫助您建立和發布產品,而無需浪費數百小時組裝不同的 npm 包。 在基礎層面上,AdonisJS 為您的應用程式提供架構,配置無縫的 TypeScript 開發環境,為您的後端程式碼配置 HMR,並提供大量維護良好且記錄廣泛的軟體包。 他們強調了一點測試,這是非常好的。 ![測試](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g623aysi86rucg45yvru.png) 開始使用以下 npm 指令。 ``` npm init adonisjs@latest hello-world ``` AdonisJS 採用經典的 MVC 設計模式。首先,使用函數式 JavaScript API 定義路由,將控制器綁定到它們,並編寫邏輯來處理控制器內的 HTTP 請求。 ``` import router from '@adonisjs/core/services/router' import PostsController from '#controllers/posts_controller' router.get('posts', [PostsController, 'index']) ``` 控制器可以使用模型從資料庫中獲取資料並呈現視圖(也稱為模板)作為回應。 ``` import { HttpContext } from '@adonisjs/core/http' import Post from '#models/post' export default class PostsController { async index({ view }: HttpContext) { const posts = await Post.all() return view.render('pages/posts/list', { posts }) } } ``` 如果您正在建立 API 伺服器,則可以用 JSON 回應取代視圖層。但是,處理和回應 HTTP 請求的流程保持不變。 您可以閱讀[文件](https://docs.adonisjs.com/guides/introduction)。 您也可以參考[入門套件](https://docs.adonisjs.com/guides/installation#starter-kits)。 他們還提供了[VSCode 擴展,](https://marketplace.visualstudio.com/items?itemName=jripouteau.adonis-vscode-extension)如果您開始使用 Adonisjs,則應該使用該擴展。 您必須查看[Awesome Adonisjs](https://github.com/adonisjs-community/awesome-adonisjs) ,它提供了一系列很棒的書籤、軟體包、教程、影片、課程、擁有使用此內容的網站的公司以及來自 AdonisJS 生態系統的其他很酷的資源。 大多數時候,開始接觸一些非常新的東西是很困難的,因此團隊提供了[10 多個課程](https://adonismastery.com/)來了解 Adonisjs 生態系統。 ![培訓班](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nkhw95z0kxkg4wcopzxb.png) ![培訓班](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iqisrlqefivdt8ozfwzv.png) 他們在 GitHub 上擁有超過 15k 個 star,並且發布了`v6.8`版本。 {% cta https://github.com/adonisjs/core %} 明星 AdonisJS ⭐️ {% endcta %} --- 13. [Astro](https://github.com/withastro/astro) - 內容驅動網站的網頁框架。 -------------------------------------------------------------- ![阿斯特羅](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7o0f21nevycm4kaqgytq.png) Astro 是一個開源、伺服器優先的 Web 框架,它結合了靜態網站產生 (SSG) 和伺服器端渲染 (SSR) 的優點,可建立快速、SEO 友善的網站。 Astro 專門為部落格和電子商務等內容豐富的網站提供支持,並擁有良好的開發生態系統。 開始使用以下 npm 指令。 ``` npm create astro@latest ``` 您可以閱讀使用 Astro 建立的[文件](https://docs.astro.build/en/getting-started/)和[展示的網站](https://astro.build/showcase/)。其中一些真的很棒並且視覺上令人驚嘆! Astro 支援 React、Preact、Svelte、Vue、Solid、Lit、HTMX、Web 元件等。閱讀所有[記錄的功能](https://docs.astro.build/en/concepts/why-astro/#features)。 您可以按照本教學[使用 Astro 建立您的第一個部落格](https://docs.astro.build/en/tutorial/0-introduction/)。或使用主題來快速啟動您的下一個專案。其中一些是免費的,而另一些則是付費的! ![主題](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06r4rgm0e87djv8otb3o.png) 您可以看到如圖所示的加載性能,甚至我對此感到驚訝。 ![天文表演](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nctfb8xzgz6dbg1wwg99.png) 性能至關重要,尤其是在您從事商業活動時,因為高效的演算法將節省更多資金並減少麻煩。 ![表現](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a7db56tvaxi40youys75.png) 無論是在可存取性、圖標還是使用不同的庫方面,[整合選項](https://astro.build/integrations/)都是巨大的。 ![整合選項](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qezjrdyaq1pvwvq4kanm.png) 您可以觀看 Freecodecamp 提供的一小時[Astro Web 框架速成課程](https://www.youtube.com/watch?v=e-hTm5VmofI)。 {% 嵌入 https://www.youtube.com/watch?v=e-hTm5VmofI %} Astro 在 GitHub 上擁有超過 42k 顆星,處於`v4.6` (1800 多個版本),並由超過 112k 開發人員使用。 {% cta https://github.com/withastro/astro %} Star Astro ⭐️ {% endcta %} --- 14. [Fresh](https://github.com/denoland/fresh) - 下一代網路框架。 --------------------------------------------------------- ![新鮮的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3978f35p4m3xg9vf9rsg.png) Fresh 是下一代 Web 框架,專為速度、可靠性和簡單性而建置。 一些突出的特點: - 島上的客戶水合作用可達到最大程度的互動。 - 零執行時開銷意味著預設不會將 JS 傳送到客戶端。 - 無需配置。 - 開箱即用的 TypeScript 支援。 該框架使用 Preact 和 JSX 進行渲染和模板化,處理伺服器和客戶端上的任務。 此外,Fresh 消除了建造步驟的需要。您編寫的程式碼直接在伺服器端和客戶端執行。 TypeScript 或 JSX 到純 JavaScript 的轉換是在需要時動態發生的。這有助於實現極其快速的迭代周期和快速部署。 從這個開始吧。 ``` deno run -A -r https://fresh.deno.dev ``` Fresh 採用的最重要的架構決策是其對[島嶼架構模式](https://www.patterns.dev/vanilla/islands-architecture)的使用。 這意味著 Fresh 應用程式預設將純 HTML 發送到客戶端。然後,伺服器渲染頁面的某些部分可以透過互動式小工具(島嶼)獨立重新水化。 客戶端只負責渲染頁面中互動性足以保證額外工作的部分。任何純靜態內容都沒有相關的客戶端 JavaScript,因此非常輕量級。 您可以閱讀[文件](https://fresh.deno.dev/docs/introduction)。 您可以找到所有使用此建立的[網站](https://fresh.deno.dev/showcase),例如[Max Schmidt](https://mooxl.dev/)的投資組合網站。 ![使用新鮮製作的投資組合網站](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5j9xwjw86by873vjkvk0.png) 他們在 GitHub 上擁有超過 11k 個 star,並且發布了`v1.6`版本。 {% cta https://github.com/denoland/fresh %} 明星新鮮 ⭐️ {% endcta %} --- 15. [Vue.js](https://github.com/vuejs/core) - 用於在網路上建立 UI 的漸進式 JavaScript 框架。 ----------------------------------------------------------------------------- ![看法](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2a8rdd0xohokbf0mx35q.png) Vue.js 是一個漸進式框架,因為它能夠透過雙整合模式促進高階單頁 Web 應用程式的設計。閱讀[使用 Vue 的所有方法](https://vuejs.org/guide/extras/ways-of-using-vue.html),包括從嵌入 Web 元件到獨立腳本,甚至使用伺服器端渲染或靜態網站生成來建立複雜的應用程式。 ![vue 用例](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nxetclturvms3ve712u9.png) 使用 MVVM(模型-視圖-視圖模型)架構,Vue.js 讓事情變得簡單、靈活且適合初學者。 Vue.js 於 2014 年由 Google 的開發人員 Evan You 首次推出,他從 AngularJS 中汲取靈感,提供了一種簡單、輕量級且高效的替代方案。 Vue.js 借用了 ReactJS 和 AngularJS 的一些功能,並對其進行了增強,以提供更流暢、更用戶友好的體驗。例如,Vue.js 將 AngularJS 的 2 路資料綁定與 React 的高效虛擬 DOM 結合。 與 React 不同,Vue 有一個內建的 MVC,可以快速輕鬆地進行設定。此外,Vue.js 的壓縮版本只有 18-20 kb,比其臃腫笨重的競爭對手(如 React 或 AngularJS)輕得多。 Vue.js 還包含一個方便的內建 CSS 過渡和動畫元件。 100 秒觀看 Vue.js 了解更多! {% 嵌入 https://www.youtube.com/watch?v=nhBVL41-\_Cw&amp;pp=ygUXZW1iZXIganMgaW4gMTAwIHNlY29uZHM%3D %} 開始使用以下 npm 指令。 ``` npm create vue@latest ``` 該命令將安裝並執行 create-vue,官方的 Vue 專案腳手架工具。您將收到有關多個可選功能的提示,例如 TypeScript 和測試支援。 這是啟動開發伺服器的方法。 ``` cd <your-project-name> npm install npm run dev ``` 一個簡單的應用程式。 ``` import { createApp } from 'vue' createApp({ data() { return { count: 0 } } }).mount('#app') <div id="app"> <button @click="count++"> Count is: {{ count }} </button> </div> ``` 上面的例子展示了Vue的兩個核心特性: 1. **聲明式渲染**:Vue 使用模板語法擴充了標準 HTML,該模板語法基於 JavaScript 狀態以聲明方式描述 HTML 輸出。 2. **反應性**:Vue 會自動追蹤 JavaScript 狀態變化,並在變化發生時有效地更新 DOM。 您也可以使用 CDN 來使用它,CDN 將使用全域建置。閱讀[快速入門指南](https://vuejs.org/guide/quick-start)以了解更多資訊。 您可以閱讀[文件](https://vuejs.org/guide/introduction)並查看不同主題的[程式碼編輯器範例](https://vuejs.org/examples/#hello-world),甚至可以了解如何建立 Markdown 編輯器。 要體驗 Vue.js,您也可以直接在他們的[現場 Playground](https://play.vuejs.org/#eNp9kVFLwzAQx7/KeS9TmBuiT6MOVAbqg4oKvuSltLeuM01CcpmF0u/utaXVhzEISe7/vyS/yzV459ziEAlXmITMl47XylDtrGfIaZtGzdAoA5CnnJ5fDHsATxy9GSOAKhQrmD2S1ha+rNf52Wyw2m6RSUaynB6QgKlyOmWSCCDZXa2bprsF2jZZStSrpXGR4XBZ2Zz0rULxFYqVLKfTOEcOmTXbsljsgzVSRw+lMLOVKzX5V8elNUHhasRVmArnz3OvsY80H/VsR9n3EX0f6k5T+OYpkD+Qwsnj1BfEg735eKFa9pMp5FFL9gnznYLVsWMc0u6jyQX7X15P+1R1PSlN8Rk2NZMJY1EdaP/Jfb5CaebDidL/cK8XN2NzsP0F+HSp8w==)中嘗試。 我非常喜歡的一篇關於 Vue 的文章是 Michael 在 DEV 上發表的。必讀! {% 嵌入 https://dev.to/michaelthiessen/25-vue-tips-you-need-to-know-2h70 %} 如果您剛開始,您可以按照他們的團隊建立的[官方教程](https://vuejs.org/tutorial/#step-1)進行操作。 ![教學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sf7dhgd0843jkpru9y27.png) 與 Astro 類似,他們也有[課程部分](https://www.vuemastery.com/courses/)和[Vue School](https://vueschool.io/) ,您可以在其中找到各種主題。 ![賽車視圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s4gixw8cd2ltkippi68h.png) Vue.js 為許多知名網站提供支持,包括 Font Awesome、Upwork 和 Namecheap 等。 Freecodecamp 有一個[針對初學者的 3 小時 Vue](https://www.youtube.com/watch?v=4deVCNJq3qc)教程,但我不推薦它,因為它是 2019 年的,而且我們知道這些框架中的概念變化有多快。 他們在 GitHub 上擁有超過 44k 個 star,並且發布了`v3.4`版本。它是有史以來最受開發人員喜愛的框架之一。 {% cta https://github.com/vuejs/core %} Star Vuejs ⭐️ {% endcta %} --- 還有很多其他框架,您可以查看其中一些: [Aurelia.js](https://github.com/aurelia/framework) 、 [Mithril.js](https://github.com/MithrilJS/mithril.js) 、 [Stimulus.js](https://github.com/hotwired/stimulus) 、 [Meteor.js](https://github.com/meteor/meteor) 、 [Angular.js](https://github.com/angular/angular) 、 [React.js](https://github.com/facebook/react) 、 [Knockout.js](https://github.com/knockout/knockout)和[Alpine.js](https://github.com/alpinejs/alpine) 。 是的,我知道,我同時感到 😵 和興奮。哈哈! 我有一些影片推薦,可以讓本文更加深入。 {% 嵌入 https://www.youtube.com/watch?v=cuHDQhDhvPE&amp;pp=ygUXZW1iZXIganMgaW4gMTAwIHNlY29uZHM%3D %} {% 嵌入 https://www.youtube.com/watch?v=WJRf7dh5Zws&amp;pp=ygURZW1iZXIganMgdHV0b3JpYWw%3D %} --- 我特意製作了這一系列教程,以幫助您在一個地方找到所有內容。我希望你喜歡這個! 雖然我是 Next.js 的忠實粉絲,但探索 Wing 等其他出色的框架可能非常適合您的下一個專案。 讓我們知道您計劃使用哪些框架,或者您認為其他人是否應該了解其他內容。 祝你有美好的一天!直到下一次。 我建立技術內容是為了幫助其他人每天成長 1%,這樣您就可以在 Twitter 和 LinkedIn 上關注我以獲得每日見解。 |如果你喜歡這類東西, 請關注我以了解更多:) | [![用戶名 Anmol_Codes 的 Twitter 個人資料](https://img.shields.io/badge/Twitter-d5d5d5?style=for-the-badge&logo=x&logoColor=0A0209)](https://twitter.com/Anmol_Codes) [![用戶名 Anmol-Baranwal 的 GitHub 個人資料](https://img.shields.io/badge/github-181717?style=for-the-badge&logo=github&logoColor=white)](https://github.com/Anmol-Baranwal) [![用戶名 Anmol-Baranwal 的 LinkedIn 個人資料](https://img.shields.io/badge/LinkedIn-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/Anmol-Baranwal/) | |------------|----------| 關注Winglang以獲取更多此類內容。 {% 嵌入 https://dev.to/winglang %} --- 原文出處:https://dev.to/winglang/15-javascript-frameworks-for-your-next-project-1o7n

我們在使用 Rust 建構 SaaS 時學到了什麼

在這篇文章中,我們**不會**回答每個人在開始新專案時都會問的問題:**我應該用 Rust 來做嗎?** ![](https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExNHQwOTl6Ym5odmVmNDZpdzVmZG9mMW9yd2tmN2lyZ2NzOWNxc2MxMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/l83rkRUu4IqyUbt5k6/giphy.gif) 相反,我們將探索在自信地回答「**絕對!** 」並開始主要使用 Rust 建立業務後遇到的陷阱和見解。 這篇文章旨在提供我們經驗的高層次概述,我們將在即將推出的系列中更深入地研究細節。 (在評論中為我們的下一篇文章投票🗳️) --- 為什麼生鏽 ----- 為專案選擇正確的語言從來不是一個一刀切的決定。 關於我們的團隊和用例的幾句話: - 我們是一個 6 人團隊,幾乎沒有 Rust 經驗,但擁有建立資料密集型應用程式的豐富 Scala/Java 背景 - 我們的 SaaS 是一個計費平台,專注於分析、即時資料和可操作的見解(想想 Stripe Billing 與 Profitwell 的結合,再加上一點 Posthog)。 - 我們的後端完全採用 Rust(分為 2 個模組和幾個工作線程),並使用 gRPC-web 與我們的 React 前端進行對話 > 我們是開源的! > 您可以在這裡找到我們的儲存庫:https://github.com/meteroid-oss/meteroid > 我們期待您的支持 ⭐ 和貢獻 因此,我們有一些不可協商的要求恰好非常適合 Rust:**效能、安全性和並發性**。 Rust 實際上消除了與記憶體管理相關的所有 bug 和 CVE,而它的並發原語非常有吸引力(並且沒有讓人失望)。 在 SaaS 中,所有這些功能在處理敏感或關鍵任務時尤其有價值,例如我們案例中的計量、發票計算和交付。 正如[包括微軟在內的](https://mspoweruser.com/microsoft-forms-new-team-to-help-rewrite-core-windows-components-into-rust-from-c-c/)許多大型企業最近所承認的那樣,其記憶體使用量的顯著減少也是建立可擴展和**永續**平台的一大優勢。 來自戲劇性的、有時有毒的 Scala 社區,**熱情且包容的**Rust 生態系統也是一個重要的吸引力,為探索這個新領域提供了動力。 帶著這樣的厚望,讓我們開始我們的旅程吧! --- 第 1 課:學習曲線是真的 ------------- 學習 Rust 並不像學習另一種語言。所有權、借用和生命週期等概念一開始可能會讓人望而生畏,使得原本瑣碎的程式碼變得極其耗時。 儘管生態系統令人愉快(稍後會詳細介紹),但有時**您不可避免地需要編寫較低層級的程式碼**。 例如,考慮我們的 API (Tonic/Tower) 的一個相當基本的中間件,它只報告計算持續時間: ``` impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for MetricService<S> where S: Service<Request<ReqBody>, Response = Response<ResBody>, Error = BoxError> + Clone + Send + 'static, S::Future: Send + 'static, ReqBody: Send, { type Response = S::Response; type Error = BoxError; type Future = ResponseFuture<S::Future>; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { self.inner.poll_ready(cx) } fn call(&mut self, request: Request<ReqBody>) -> Self::Future { let clone = self.inner.clone(); let mut inner = std::mem::replace(&mut self.inner, clone); let started_at = std::time::Instant::now(); let sm = GrpcServiceMethod::extract(request.uri()); let future = inner.call(request); ResponseFuture { future, started_at, sm, } } } #[pin_project] pub struct ResponseFuture<F> { #[pin] future: F, started_at: Instant, sm: GrpcServiceMethod, } impl<F, ResBody> Future for ResponseFuture<F> where F: Future<Output = Result<Response<ResBody>, BoxError>>, { type Output = Result<Response<ResBody>, BoxError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); let res = ready!(this.future.poll(cx)); let finished_at = Instant::now(); let delta = finished_at.duration_since(*this.started_at).as_millis(); // this is the actual logic let (res, grpc_status_code) = (...) crate::metric::record_call( GrpcKind::SERVER, this.sm.clone(), grpc_status_code, delta as u64, ); Poll::Ready(res) } } ``` 是的,除了泛型類型、泛型生命週期和特徵約束之外,您最終還需要為簡單的服務中間件編寫自訂的 Future 實作。 請記住,這是一個有點極端的例子,旨在展示生態系統中存在的粗糙邊緣。*在許多情況下,Rust 最終可以像任何其他現代語言一樣緊湊。* **學習曲線可能會根據您的背景而有所不同。**如果您習慣了 JVM 處理繁重的工作並像我們一樣使用更成熟、更廣泛的生態系統,那麼可能需要付出更多的努力來理解 Rust 的獨特概念和範例。 然而,一旦您掌握了這些概念和原語,它們就會成為您武器庫中極其強大的工具,即使您偶爾需要編寫一些樣板文件或宏,也可以提高您的工作效率。 值得一提的是, [Google 在相當短的時間內成功地將團隊從 Go 和 C++ 過渡到 Rust,](https://www.theregister.com/2024/03/31/rust_google_c)並且取得了積極的成果。 要平滑學習曲線,請考慮以下因素: - **閱讀官方[Rust Book 的](https://doc.rust-lang.org/stable/book/)封面**。不要跳過章節。理解這些複雜的概念將變得容易得多。 - **練習,練習,練習!**透過[Rustlings](https://rustlings.cool/)練習來建立肌肉記憶並採用 Rust 思維方式。 - **參與[Rust 社群](https://www.reddit.com/r/rust/)。**他們是一群令人難以置信的人,總是願意伸出援手。 - **利用 GitHub 的搜尋**功能尋找其他專案並向其學習。生態系統仍在不斷發展,與其他人的合作至關重要(只需注意許可證並始終做出貢獻)。 我們將在下一篇文章中探討一些帶給我們啟發的專案。 --- 教訓 2:生態系仍處於成熟階段 --------------- Rust 的底層生態系統確實令人難以置信,擁有精心設計和維護的庫,並被社區廣泛採用。這些函式庫為建構高效能且可靠的系統奠定了堅實的基礎。 然而,當你在堆疊中向上移動時,事情可能會變得稍微複雜一些。 ![](https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExeWNoejRsb2RhaGsybzQwdXJydjJzbHVpNjR6eW9udzdudjlvdWVjdiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/l2SpOlC7JLROBEkO4/giphy.gif) 例如,在資料庫生態系統中,雖然針對關聯式資料庫存在像[`sqlx`](https://github.com/launchbadge/sqlx)和[`diesel`](https://github.com/diesel-rs/diesel)這樣的優秀函式庫,但對於許多非同步或非關聯式資料庫用戶端來說,情況會更加複雜。這些領域的高品質庫,即使被大公司使用,也往往只有**單一維護者**,導致開發速度較慢並且有潛在的維護風險。 對於分散式系統原語來說,挑戰更為明顯,您可能需要實現自己的解決方案。 這並不是 Rust 所獨有的,但與舊的/更成熟的語言相比,我們經常發現自己處於這種情況。 從好的方面來說, **Rust 的生態系統對安全問題的反應令人印象深刻**,補丁迅速傳播,確保了應用程式的穩定性和安全性。 到目前為止,圍繞 Rust 開發的工具也非常令人驚嘆。 我們將在以後的文章中深入探討我們選擇的函式庫以及我們所做的決定。 生態系統不斷發展,社區積極努力填補空白並提供強大的解決方案。準備好探索未知領域,並相應地分配資源以幫助維護,並回饋社區。 --- ### ……我有沒有提到我們是開源的? > [Metroid](https://meteroid.com/)是一個現代化的開源計費平台,專注於商業智慧和可操作的見解。 **我們需要你的幫助 !如果你有一分鐘時間,** [](https://git.new/meteroid) ![](https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExZDFvd2M3bnZ4OTF1dzBkcHh1NnlwemY1cTU5NWVjOThoZjU4a2U5biZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/XATW2O9w0hrmuIpvtu/giphy.gif) 您的支持對我們意義重大❤️ https://github.com/meteroid-oss/meteroid ⭐️ 在 Github 上為我們加註星標 ⭐️ --- 第 3 課:文件位於程式碼中 -------------- 當深入 Rust 的生態系統時,您很快就會意識到文件網站有時可能有點......好吧,稀疏。 但不要害怕!真正的寶藏往往存在於原始碼中。 許多庫都有**非常詳細的方法記錄,**並**在程式碼註釋中**包含全面的範例。如有疑問,請深入研究原始程式碼並進行探索。您經常會發現您尋求的答案,並對圖書館的內部運作有更深入的了解。 雖然具有使用指南的外部文件仍然很重要,並且可以節省開發人員的時間和挫折感,但在 Rust 生態系統中,準備好在必要時深入研究程式碼至關重要。 像[docs.rs](https://docs.rs)這樣的網站可以輕鬆存取公共 Rust 套件的基於程式碼的文件。或者,您可以使用 Cargo doc 在本機上產生所有依賴項的文件。這種方法一開始可能會令人困惑,但從長遠來看,花一些時間學習如何駕馭這個系統可能會非常有效。 不用說,另一個有用的技術是尋找範例(**大多數庫在其存儲庫中都有一個`/examples`資料夾**)和使用您感興趣的庫的其他專案,並與這些社區互動。這些總是為如何使用該庫提供有價值的指導,並且可以作為您自己實施的起點。 --- 第四課:不要追求完美 ---------- 當開始使用 Rust 時,人們很容易會努力爭取最慣用和最高效能的程式碼。 然而,大多數時候,以簡單性和生產力的名義進行權衡是可以的。 ![做完比求完美強](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fylenuk9pzgynzsvbwpf.png) 例如,使用`clone()`或`Arc`在執行緒之間共享資料可能不是最節省記憶體的方法,但它可以極大地簡化程式碼並提高可讀性。只要您意識到效能影響並做出明智的決策,**優先考慮簡單性是完全可以接受的。** 請記住,過早的優化是萬惡之源。首先專注於編寫乾淨、可維護的程式碼,然後在必要時進行最佳化。**不要嘗試進行微優化(**除非您確實需要)。 Rust 強大的類型系統和所有權模型已經為編寫高效、安全的程式碼提供了堅實的基礎。 當需要優化效能時,請專注於關鍵路徑並使用`perf`和`flamegraph`等分析工具來辨識程式碼中的真正效能熱點。對於工具和技術的全面概述,我可以推薦[The Rust Performance Book](https://nnethercote.github.io/perf-book/introduction.html) 。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eyudtxuaeswhtc9porfc.png) **¹**這適用於您的整個創業歷程,包括籌款 --- 第五課:錯誤畢竟是好事 ----------- Rust 的錯誤處理非常優雅,具有`Result`類型和`?`運算符鼓勵明確的錯誤處理和傳播。然而,這不僅涉及處理錯誤;還涉及處理錯誤。它還涉及提供乾淨且資訊豐富的錯誤訊息以及可追蹤的堆疊追蹤。 無需大量樣板在錯誤類型之間進行轉換。 像`thiserror` , `anyhow`或`snafu`函式庫對於這個目的來說是無價的。我們決定使用`thiserror` ,它可以簡化帶有資訊性錯誤訊息的自訂錯誤類型的建立。 在大多數 Rust 用例中,您不太關心底層錯誤類型堆疊跟踪,而是更喜歡將其直接映射到域中的訊息類型錯誤。 ``` #[derive(Debug, Error)] pub enum WebhookError { #[error("error comparing signatures")] SignatureComparisonFailed, #[error("error parsing timestamp")] BadHeader(#[from] ParseIntError), #[error("error comparing timestamps - over tolerance.")] BadTimestamp(i64), #[error("error parsing event object")] ParseFailed(#[from] serde_json::Error), #[error("error communicating with client : {0}")] ClientError(String), } ``` 投入時間製作清晰且資訊豐富的錯誤訊息可以大大增強開發人員的體驗並簡化偵錯。這是一個小小的努力,卻可以產生顯著的長期效益。 然而,有時,甚至在日誌位於使用者範圍之外的 SaaS 用例中,保留完整的錯誤鏈以及沿途可能有額外的上下文是很有意義的。 我們目前正在試驗[`error-stack`](https://github.com/hashintel/hash/tree/main/libs/error-stack) ,這是一個由 hash.dev 維護的庫,它允許附加額外的上下文並將其保留在整個錯誤樹中。它作為`thiserror`之上的一層效果很好。 它提供了一個慣用的 API,實際上將錯誤類型包裝在報告資料結構中,該資料結構保留了所有錯誤、原因和您可能加入的任何其他上下文的堆疊,在發生故障時提供大量資訊。 我們遇到了一些問題,但這篇文章已經太長了,更多內容將在後續文章中介紹! 總結 --- 使用 Rust 建立我們的 SaaS 一直是(而且仍然是)一段旅程。一開始是一段漫長而充滿挑戰的旅程,但也是一段非常有趣且有益的旅程。 - **使用 Scala 可以更快地建立我們的產品嗎?** 當然。 - **會有那麼有效嗎?** 或許。 - **我們還會像今天一樣充滿熱情和興奮嗎?** 可能不會。 Rust 促使我們以不同的方式思考我們的程式碼,接受新的範式,並不斷努力改進。 **當然,Rust 也有其粗糙的一面**。學習曲線可能很陡峭,而且生態系統仍在不斷發展。但這是令人興奮的一部分。 除了技術面之外, **Rust 社群也絕對令人高興**。熱情的氛圍、樂於助人的意願以及對語言的共同熱情使這趟旅程變得更加愉快。 ![](https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExazJlZGppYjY5M3RwOG5sdHdudW94dzk4eXczZm5iMmN0YWUzdG10NyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/sn39fEb1LcHPGQ4b6h/giphy.gif) 因此,如果您有時間和意願去探索一個新的、蓬勃發展的生態系統,如果您願意接受挑戰並從中學習,如果您需要表現、安全性和並發性,那麼**Rust 可能只是成為適合您的語言**。 對我們來說,我們很高興能夠繼續使用 Rust 建立我們的 SaaS,不斷學習和成長,並看看這段旅程將帶我們走向何方。請繼續關注更深入的帖子,或在第一條評論中投票選出我們下一步應該做的事情。 如果您喜歡這篇文章並發現它有幫助,請不要忘記給[我們的儲存庫](https://github.com/meteroid-oss/meteroid)一顆星!您的支持對我們來說意味著整個世界。 https://github.com/meteroid-oss/meteroid ⭐️ 流星星 ⭐️ 下次見,祝您編碼愉快! --- 原文出處:https://dev.to/meteroid/5-lessons-learned-building-our-saas-with-rust-1doj

深入探討 Javascript 函數式編程

[訂閱我的程式設計 YouTube 頻道](https://www.youtube.com/@alexmercedcoder) [訂閱我的資料 YouTube 頻道](https://www.youtube.com/@alexmerceddata) 函數式程式設計 (FP) 在軟體開發領域獲得了巨大的關注,JavaScript 開發人員越來越多地轉向這種範例,以更有效地解決問題並減少錯誤。從本質上講,函數式程式設計強調使用純函數、不變性以及柯里化、記憶化和 monad 等先進技術來建立更清晰、更可預測的程式碼。 在這篇文章中,我們將深入研究每個概念,以了解它們的工作原理以及它們在 JavaScript 開發中的重要性。我們將探索**純函數**的無副作用性質、用於維護狀態可預測性的**不變性**、用於增強函數重用和組合的**柯里化**、用於優化性能的**記憶化**以及用於以函數式風格處理副作用的**monad** 。 無論您是函數式程式設計的新手,還是希望加深對其在 JavaScript 中的應用的理解,這篇文章都將為您提供堅實的基礎和實際範例,以便將這些原則整合到您的編碼實踐中。讓我們揭開這些概念的神秘面紗,看看它們如何改變您編寫 JavaScript 程式碼的方式。 1. 純函數 ------ **純函數**是一種函數,在給定相同的輸入的情況下,將始終返回相同的輸出,並且不會導致任何可觀察到的副作用。這個概念在函數式程式設計中至關重要,因為它允許開發人員編寫更可預測和可測試的程式碼。 ### 在 JavaScript 中使用純函數的好處: - **可預測性:**由於純函數不依賴或修改其範圍之外的資料狀態,因此它們更容易推理和除錯。 - **可重複使用性:**純函數可以在應用程式的不同部分重複使用,而無需考慮外部上下文。 - **可測試性:**沒有隱藏狀態或副作用,純函數很容易測試;輸入和輸出是您需要考慮的全部。 ### JavaScript 中純函數的範例: 考慮一個簡單的函數來計算矩形的面積: ``` function rectangleArea(length, width) { return length * width; } ``` 這個函數是純粹的,因為它總是使用相同的參數來傳回相同的結果,而且它不會修改任何外部狀態或產生副作用。 ### 常見陷阱以及如何避免它們: 雖然純函數提供了許多好處,但開發人員在嘗試將它們整合到與資料庫、外部服務或全域狀態互動的應用程式時可能會面臨挑戰。以下是保持純度的一些技巧: - **避免副作用:**不要修改函數內的任何外部變數或物件。 - **本機處理狀態:**如果您的函數需要存取應用程式狀態,請考慮將狀態作為參數傳遞並傳回新狀態而不修改原始狀態。 透過理解和實現純函數,開發人員可以在充分利用 JavaScript 中函數式程式設計的全部功能方面邁出重要一步。 2. 不變性 ------ **不變性**是指資料建立後永不更改的原則。您無需修改現有物件,而是建立一個包含所需變更的新物件。這是函數式程式設計的基石,因為它有助於防止副作用並在應用程式的整個生命週期中保持資料的完整性。 ### JavaScript 如何處理不變性: 預設情況下,JavaScript 物件和陣列是可變的,這表示在需要時必須注意強制執行不變性。但是,有幾種技術和工具可以提供幫助: - **使用`const` :**雖然`const`不會使變數變得不可變,但它可以防止將變數辨識碼重新指派給新值,這是邁向不變性的一步。 - **Object.freeze():**此方法可以透過防止向物件新增屬性和修改現有屬性來使物件不可變。 - **陣列和物件的擴展語法:**使用擴展語法可以幫助建立新的陣列或物件,同時合併現有陣列或物件的元素或屬性,而無需修改原始陣列或物件。 ### 確保 JavaScript 中資料不變性的技術: 1. **寫入時複製:**始終建立一個新的物件或陣列,而不是修改現有的物件或陣列。例如: ``` const original = { a: 1, b: 2 }; const modified = { ...original, b: 3 }; // 'original' is not changed ``` 2. **使用函式庫:**像 Immutable.js 這樣的函式庫提供了高度最佳化的持久不可變資料結構,可以簡化不變性的實作。 ### 幫助實施不變性的函式庫: - **Immutable.js:**提供一系列本質上不可變的資料結構。 - **immer:**允許您透過使用臨時草稿狀態並套用變更來產生新的不可變狀態,以更方便的方式處理不可變狀態。 透過將不變性整合到 JavaScript 專案中,您可以增強資料完整性、提高應用程式效能(透過減少防禦性複製的需求)並提高程式碼的可預測性。它完全符合函數式程式設計的原則,從而產生更乾淨、更健壯的軟體。 3.柯里化 ----- **柯里化**是函數式程式設計中的一種變革性技術,其中具有多個參數的函數被轉換為一系列函數,每個函數採用一個參數。這種方法不僅使您的函數更加模組化,而且還增強了程式碼的可重複使用性和可組合性。 ### JavaScript 柯里化的實際用途: 柯里化允許建立高階函數,這些函數可以在應用程式的不同點使用不同的參數進行自訂和重複使用。它特別適用於: - **事件處理:**建立針對特定事件自訂的部分應用函數,但重複使用通用處理程序邏輯。 - **API 呼叫:**使用預定義參數(例如 API 金鑰或使用者 ID)設定函數,這些參數可以在不同的呼叫中重複使用。 ### 說明柯里化的逐步範例: 考慮一個簡單的函數來加兩個數字: ``` function add(a, b) { return a + b; } // Curried version of the add function function curriedAdd(a) { return function(b) { return a + b; }; } const addFive = curriedAdd(5); console.log(addFive(3)); // Outputs: 8 ``` 此範例展示了柯里化如何將簡單的加法函數轉變為更通用和可重複使用的函數。 ### 柯里化與部分應用: 雖然柯里化和部分應用都涉及將函數分解為更簡單、更具體的函數,但它們並不相同: - **柯里化(Currying):**將具有多個參數的函數轉換為一系列巢狀函數,每個函數只接受一個參數。 - **部分應用:**涉及透過預先填充一些參數來建立具有較少參數的函數。 這兩種技術在函數式程式設計中都很有價值,可以用來簡化複雜的函數簽名並提高程式碼模組化。 透過利用柯里化,開發人員可以增強函數的可重複使用性和組合性,從而在 JavaScript 專案中產生更清晰、更易於維護的程式碼。 4. 記憶 ----- **記憶化**是函數式程式設計中使用的最佳化技術,透過儲存昂貴的函數呼叫的結果並在相同的輸入再次發生時返回快取的結果來加速電腦程式。它在 JavaScript 中對於優化涉及繁重計算任務的應用程式的效能特別有用。 ### 為什麼記憶化在 JavaScript 很重要: - **效率:**減少使用相同參數重複呼叫函數所需的計算次數。 - **效能:**透過快取耗時操作的結果來提高應用程式回應能力。 - **可擴展性:**透過最小化計算開銷來幫助管理更大的資料集或更複雜的演算法。 ### 實現記憶化:範例和常用方法: 以下是 JavaScript 中記憶函數的基本範例: ``` function memoize(fn) { const cache = {}; return function(...args) { const key = args.toString(); if (!cache[key]) { cache[key] = fn.apply(this, args); } return cache[key]; }; } const factorial = memoize(function(x) { if (x === 0) { return 1; } else { return x * factorial(x - 1); } }); console.log(factorial(5)); // Calculates and caches the result console.log(factorial(5)); // Returns the cached result ``` 此範例示範了記憶化如何快取階乘計算的結果,從而顯著減少重複呼叫的計算時間。 ### 記憶化的優點和潛在缺點: #### 好處: - 顯著減少重複操作的處理時間。 - 透過避免冗餘計算來提高應用程式效率。 - 易於用高階函數實現。 #### 缺點: - 由於快取而增加記憶體使用量。 - 不適合具有不確定性輸出的函數或具有副作用的函數。 透過理解和實現記憶化,開發人員可以優化他們的 JavaScript 應用程式,使其更快、更有效率。然而,重要的是要考慮額外記憶體使用方面的權衡,並確保僅在能夠提供明顯好處的地方應用記憶化。 5. 單子 ----- **Monad**是函數式程式設計中使用的抽象資料類型,用於處理副作用,同時保持純函數原則。它們將行為和邏輯封裝在靈活的可連結結構中,允許順序操作,同時保持函數的純淨。 ### Monad 簡介及其在 FP 中的意義: Monad 提供了一個以受控方式處理副作用(如 IO、狀態、異常等)的框架,有助於保持功能的純度和可組合性。在 JavaScript 中,Promise 是一個常見的一元結構範例,可以乾淨且有效率地管理非同步操作。 ### JavaScript 中 Monad 的範例: - **Promises:**透過封裝待處理操作、成功值或錯誤來處理非同步操作,允許方法連結(如`.then()`和`.catch()` ): ``` new Promise((resolve, reject) => { setTimeout(() => resolve("Data fetched"), 1000); }) .then(data => console.log(data)) .catch(error => console.error(error)); ``` - **Maybe Monad:**透過封裝可能存在或不存在的值來幫助處理 null 或未定義的錯誤: ``` function Maybe(value) { this.value = value; } Maybe.prototype.bind = function(transform) { return this.value == null ? this : new Maybe(transform(this.value)); }; Maybe.prototype.toString = function() { return `Maybe(${this.value})`; }; const result = new Maybe("Hello, world!").bind(value => value.toUpperCase()); console.log(result.toString()); // Outputs: Maybe(HELLO, WORLD!) ``` ### Monad 定律與結構: Monad 必須遵循三個核心定律——同一性、關聯性和單位——以確保它們的行為可預測: - **同一性:**直接應用函數或透過 monad 傳遞函數應該會產生相同的結果。 - **關聯性:**執行操作的順序(連結)不影響結果。 - **單位:**一個值必須能夠被提升為一個單子而不改變其行為。 理解這些定律對於在函數式程式設計中有效地實現或利用 monad 至關重要。 ### Monad 如何管理副作用並保持功能純度: 透過封裝副作用,monad 允許開發人員保持程式碼庫的其餘部分純淨,從而更易於理解和維護。它們使副作用可預測和可管理,這對於維護狀態一致性和錯誤處理可能變得具有挑戰性的大型應用程式至關重要。 透過利用 monad,開發人員可以增強 JavaScript 應用程式的功能,確保它們以功能性的方式處理副作用,從而提高程式碼的可靠性和可維護性。 6. 這些概念如何相互關聯 ------------- 純函數、不變性、柯里化、記憶化和 monad 的概念不僅僅是單獨的元素,而是增強 JavaScript 應用程式的健全性和可維護性的互連工具。以下是他們如何共同創造一個有凝聚力的函數式程式設計環境。 ### 建立功能協同: - **純函數與不變性:**純函數確保函數沒有副作用,並為相同的輸入傳回相同的輸出,並透過防止資料意外變更的不變性來補充。它們共同確保了可預測且穩定的程式碼庫。 - **柯里化和記憶化:**柯里化允許將函數分解為更簡單的單參數函數,這些函數更易於管理和記憶。然後可以將記憶化應用於這些柯里化函數以緩存其結果,透過避免重複計算來優化應用程式的效能。 - **Monad 和純函數:** Monad 有助於以受控方式管理副作用,這使得純函數即使在處理 I/O 或狀態轉換等操作時也能保持純淨。這種副作用的封裝保留了功能架構的完整性。 ### 範例:一個小型功能模組: 讓我們考慮一個將這些概念結合在一起的實際範例。假設我們正在建立一個簡單的用戶註冊模組: ``` // A pure function to validate user input const validateInput = input => input.trim() !== ''; // A curried function for creating a user object const createUser = name => ({ id: Date.now(), name }); // Memoizing the createUser function to avoid redundant operations const memoizedCreateUser = memoize(createUser); // A monad for handling potential null values in user input const getUser = input => new Maybe(input).bind(validateInput); // Example usage const input = getUser(' John Doe '); const user = input.bind(memoizedCreateUser); console.log(user.toString()); // Outputs user details or empty Maybe ``` 在此範例中, `validateInput`是確保輸入有效性的純函數。 `createUser`是一個柯里化和記憶化的函數,針對效能進行了最佳化,而`getUser`使用 monad 來安全地處理潛在的 null 值。 結論: --- 理解和整合這些函數式程式設計概念可以顯著提高 JavaScript 程式碼的品質和可維護性。透過同時使用純函數、不變性、柯里化、記憶化和 monad,開發人員可以建立更可靠、更有效率、更乾淨的應用程式。 透過採用這些相互關聯的原則,JavaScript 開發人員可以充分利用函數式程式設計的潛力來編寫更好、更永續的程式碼。 --- 原文出處:https://dev.to/alexmercedcoder/deep-dive-into-functional-programming-in-javascript-851

如何讓 AI 融入您的使用者(Next.js、OpenAI、CopilotKit)

長話短說 ---- 在本文中,您將了解如何建立基於 AI 的行銷活動管理應用程式,該應用程式可讓您建立和分析廣告活動,從而使您能夠為您的業務做出正確的決策。 我們將介紹如何: - 使用 Next.js 建立 Web 應用程式, - 使用 CopilotKit 將 AI 助理整合到軟體應用程式中,以及 - 建立特定於操作的人工智慧副駕駛來處理應用程式中的各種任務。 - 建立一名競選經理 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xqpz356qm79t90f1l87.gif) --- CopilotKit:建構應用內人工智慧副駕駛的框架 -------------------------- CopilotKit是一個[開源的AI副駕駛平台](https://github.com/CopilotKit/CopilotKit)。我們可以輕鬆地將強大的人工智慧整合到您的 React 應用程式中。 建造: - ChatBot:上下文感知的應用內聊天機器人,可以在應用程式內執行操作 💬 - CopilotTextArea:人工智慧驅動的文字字段,具有上下文感知自動完成和插入功能📝 - 聯合代理:應用程式內人工智慧代理,可以與您的應用程式和使用者互動🤖 ![https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3 .amazonaws.com%2Fuploads%2Farticles%2Fx3us3vc140aun0dvrdof.gif](https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx3us3vc140aun0dvrdof.gif) {% cta https://git.new/devtoarticle1 %} Star CopilotKit ⭐️ {% endcta %} --- 先決條件 ---- 要完全理解本教程,您需要對 React 或 Next.js 有基本的了解。 我們還將利用以下內容: - [Radix UI](https://www.radix-ui.com/) - 用於為應用程式建立可存取的 UI 元件。 - [OpenAI API 金鑰](https://platform.openai.com/api-keys)- 使我們能夠使用 GPT 模型執行各種任務。 - [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 一個開源副駕駛框架,用於建立自訂 AI 聊天機器人、應用程式內 AI 代理程式和文字區域。 --- 專案設定和套件安裝 --------- 首先,透過在終端機中執行以下程式碼片段來建立 Next.js 應用程式: ``` npx create-next-app campaign-manager ``` 選擇您首選的配置設定。在本教學中,我們將使用 TypeScript 和 Next.js App Router。 ![Next.js 應用程式安裝](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xboujt60i6lpoaqgjyap.png) 接下來,將[Heroicons](https://www.npmjs.com/package/@heroicons/react) 、 [Radix UI](https://www.radix-ui.com/)及其原始元件安裝到專案中。 ``` npm install @heroicons/react @radix-ui/react-avatar @radix-ui/react-dialog @radix-ui/react-dropdown-menu @radix-ui/react-icons @radix-ui/react-label @radix-ui/react-popover @radix-ui/react-select @radix-ui/react-slot @radix-ui/react-tabs ``` 另外,安裝[Recharts 程式庫](https://recharts.org/en-US)(一個用於建立互動式圖表的 React 程式庫)以及以下實用程式套件: ``` npm install recharts class-variance-authority clsx cmdk date-fns lodash react-day-picker tailwind-merge tailwindcss-animate ``` 最後,安裝[CopilotKit 軟體套件](https://docs.copilotkit.ai/getting-started/quickstart-chatbot)。這些套件使 AI copilot 能夠從 React 狀態檢索資料並在應用程式中做出決策。 ``` npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend ``` 恭喜!您現在已準備好建立應用程式。 --- 使用 Next.js 建立 Campaign Manager 應用程式 ----------------------------------- 在本節中,我將引導您建立活動管理器應用程式的使用者介面。 首先,讓我們進行一些初始設定。 在`src`資料夾中建立一個`components`和`lib`資料夾。 ``` cd src mkdir components lib ``` 在**`lib`**資料夾中,我們將聲明應用程式的靜態類型和預設活動。因此,在**`lib`**資料夾中建立**`data.ts`**和**`types.ts`**檔案。 ``` cd lib touch data.ts type.ts ``` 將下面的程式碼片段複製到`type.ts`檔中。它聲明了活動屬性及其資料類型。 ``` export interface Campaign { id: string; objective?: | "brand-awareness" | "lead-generation" | "sales-conversion" | "website-traffic" | "engagement"; title: string; keywords: string; url: string; headline: string; description: string; budget: number; bidStrategy?: "manual-cpc" | "cpa" | "cpm"; bidAmount?: number; segment?: string; } ``` 為應用程式建立預設的行銷活動清單並將其複製到`data.ts`檔案中。 ``` import { Campaign } from "./types"; export let DEFAULT_CAMPAIGNS: Campaign[] = [ { id: "1", title: "CopilotKit", url: "https://www.copilotkit.ai", headline: "Copilot Kit - The Open-Source Copilot Framework", description: "Build, deploy, and operate fully custom AI Copilots. In-app AI chatbots, AI agents, AI Textareas and more.", budget: 10000, keywords: "AI, chatbot, open-source, copilot, framework", }, { id: "2", title: "EcoHome Essentials", url: "https://www.ecohomeessentials.com", headline: "Sustainable Living Made Easy", description: "Discover our eco-friendly products that make sustainable living effortless. Shop now for green alternatives!", budget: 7500, keywords: "eco-friendly, sustainable, green products, home essentials", }, { id: "3", title: "TechGear Solutions", url: "https://www.techgearsolutions.com", headline: "Innovative Tech for the Modern World", description: "Find the latest gadgets and tech solutions. Upgrade your life with smart technology today!", budget: 12000, keywords: "tech, gadgets, innovative, modern, electronics", }, { id: "4", title: "Global Travels", url: "https://www.globaltravels.com", headline: "Travel the World with Confidence", description: "Experience bespoke travel packages tailored to your dreams. Luxury, adventure, relaxation—your journey starts here.", budget: 20000, keywords: "travel, luxury, adventure, tours, global", }, { id: "5", title: "FreshFit Meals", url: "https://www.freshfitmeals.com", headline: "Healthy Eating, Simplified", description: "Nutritious, delicious meals delivered to your door. Eating well has never been easier or tastier.", budget: 5000, keywords: "healthy, meals, nutrition, delivery, fit", }, ]; ``` 由於我們使用 Radix UI 建立可以使用 TailwindCSS 輕鬆自訂的基本 UI 元件,因此請在**`lib`**資料夾中建立一個**`utils.ts`**文件,並將以下程式碼片段複製到該文件中。 ``` //👉🏻 The lib folder now contains 3 files - data.ts, type.ts, util.ts //👇🏻 Copy the code below into the "lib/util.ts" file. import { type ClassValue, clsx } from "clsx"; import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } export function randomId() { return Math.random().toString(36).substring(2, 15); } ``` 導航到`components`資料夾並在其中建立其他三個資料夾。 ``` cd components mkdir app dashboard ui ``` `components/app`資料夾將包含應用程式中使用的各種元件,而儀表板資料夾包含某些元素的 UI 元件。 `ui`資料夾包含使用 Radix UI 建立的多個 UI 元素。將[專案儲存庫中的這些元素](https://github.com/CopilotKit/campaign-manager-demo/tree/main/src/components/ui)複製到該資料夾中。 恭喜! `ui`資料夾應包含必要的 UI 元素。現在,我們可以使用它們來建立應用程式中所需的各種元件。 ### 建立應用程式 UI 元件 在這裡,我將引導您完成為應用程式建立使用者介面的過程。 ![應用程式使用者介面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9l4lvv4394gg033oatwq.png) 首先,導航至**`app/page.tsx`**檔案並將以下程式碼片段貼到其中。該文件呈現在**`components/app`**資料夾中聲明的 App 元件。 ``` "use client"; import { App } from "@/components/app/App"; export default function DashboardPage() { return <App />; } ``` 在`components/app`資料夾中建立`App.tsx` 、 `CampaignForm.tsx` 、 `MainNav.tsx`和`UserNav.tsx`檔案。 ``` cd components/app touch App.tsx CampaignForm.tsx MainNav.tsx UserNav.tsx ``` 將下面的程式碼片段複製到`App.tsx`檔案中。 ``` "use client"; import { DEFAULT_CAMPAIGNS } from "@/lib/data"; import { Campaign } from "@/lib/types"; import { randomId } from "@/lib/utils"; import { Dashboard } from "../dashboard/Dashboard"; import { CampaignForm } from "./CampaignForm"; import { useState } from "react"; import _ from "lodash"; export function App() { //👇🏻 default segments const [segments, setSegments] = useState<string[]>([ "Millennials/Female/Urban", "Parents/30s/Suburbs", "Seniors/Female/Rural", "Professionals/40s/Midwest", "Gamers/Male", ]); const [campaigns, setCampaigns] = useState<Campaign[]>( _.cloneDeep(DEFAULT_CAMPAIGNS) ); //👇🏻 updates campaign list function saveCampaign(campaign: Campaign) { //👇🏻 newly created campaign if (campaign.id === "") { campaign.id = randomId(); setCampaigns([campaign, ...campaigns]); } else { //👇🏻 existing campaign - search for the campaign and updates the campaign list const index = campaigns.findIndex((c) => c.id === campaign.id); if (index === -1) { setCampaigns([...campaigns, campaign]); } else { campaigns[index] = campaign; setCampaigns([...campaigns]); } } } const [currentCampaign, setCurrentCampaign] = useState<Campaign | undefined>( undefined ); return ( <div className='relative'> <CampaignForm segments={segments} currentCampaign={currentCampaign} setCurrentCampaign={setCurrentCampaign} saveCampaign={(campaign) => { if (campaign) { saveCampaign(campaign); } setCurrentCampaign(undefined); }} /> <Dashboard campaigns={campaigns} setCurrentCampaign={setCurrentCampaign} segments={segments} setSegments={setSegments} /> </div> ); } ``` - 從上面的程式碼片段來看, - 我為行銷活動建立了預設細分列表,並對已定義的行銷活動列表進行了深層複製。 - `saveCampaign`函數接受行銷活動作為參數。如果行銷活動沒有 ID,則表示它是新建立的,因此會將其新增至行銷活動清單。否則,它會找到該活動並更新其屬性。 - `Dashboard`和`CampaignForm`元件接受細分和行銷活動作為 props。 [Dashboard 元件](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/components/dashboard/Dashboard.tsx)在儀表板上顯示各種 UI 元素,而[CampaignForm 元件](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/components/app/CampaignForm.tsx)使用戶能夠在應用程式中建立和保存新的行銷活動。 您也可以使用[GitHub 儲存庫](https://github.com/CopilotKit/campaign-manager-demo/tree/main/src/components)中的程式碼片段來更新儀表板和應用程式元件。 恭喜!您應該有一個有效的 Web 應用程式,可讓使用者查看和建立新的行銷活動。 在接下來的部分中,您將了解如何將 CopilotKit 加入到應用程式中,以根據每個行銷活動的目標和預算進行分析和決策。 ![應用概述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4phyaucli8pdcbe625u4.gif) --- 使用 CopilotKit 透過 AI 分析廣告活動 -------------------------- 在這裡,您將學習如何將人工智慧加入到應用程式中,以幫助您分析行銷活動並做出最佳決策。 在繼續之前,請造訪[OpenAI 開發者平台](https://platform.openai.com/api-keys)並建立一個新的金鑰。 ![取得 OpenAI API 金鑰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02972pt2aj3kf9l5suqq.png) 建立一個`.env.local`檔案並將新建立的金鑰複製到該檔案中。 ``` OPENAI_API_KEY=<YOUR_OPENAI_SECRET_KEY> OPENAI_MODEL=gpt-4-1106-preview ``` 接下來,您需要為 CopilotKit 建立 API 端點。在 Next.js 應用程式資料夾中,建立一個包含`route.ts`檔案的`api/copilotkit`資料夾。 ``` cd app mkdir api && cd api mkdir copilotkit && cd copilotkit touch route.ts ``` 將下面的程式碼片段複製到`route.ts`檔中。 [CopilotKit 後端](https://docs.copilotkit.ai/reference/CopilotBackend)接受使用者的請求並使用 OpenAI 模型做出決策。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; export const runtime = "edge"; export async function POST(req: Request): Promise<Response> { const copilotKit = new CopilotBackend({}); const openaiModel = process.env["OPENAI_MODEL"]; return copilotKit.response(req, new OpenAIAdapter({ model: openaiModel })); } ``` 若要將您的應用程式連接到此 API 端點,請更新`app/page.tsx`文件,如下所示: ``` "use client"; import { App } from "@/components/app/App"; import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; export default function DashboardPage() { return ( <CopilotKit url='/api/copilotkit/'> <CopilotSidebar instructions='Help the user create and manage ad campaigns.' defaultOpen={true} labels={{ title: "Campaign Manager Copilot", initial: "Hello there! I can help you manage your ad campaigns. What campaign would you like to work on?", }} clickOutsideToClose={false} > <App /> </CopilotSidebar> </CopilotKit> ); } ``` `CopilotKit`元件包裝整個應用程式並接受包含 API 端點連結的`url`屬性。 `CopilotSidebar`元件為應用程式加入了一個聊天機器人側邊欄面板,使我們能夠向 CopilotKit 提供各種指令。 ![將 CopilotKit 加入 Next.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wzh8ui253ftzmgtrcksd.gif) ### 如何讓AI副駕駛執行各種動作 CopilotKit 提供了兩個鉤子,使我們能夠處理使用者的請求並插入應用程式狀態: [useCopilotAction](https://docs.copilotkit.ai/reference/useCopilotAction)和[useMakeCopilotReadable](https://docs.copilotkit.ai/reference/useMakeCopilotReadable) 。 `useCopilotAction`掛鉤可讓您定義 CopilotKit 執行的動作。它接受包含以下參數的物件: - name - 操作的名稱。 - 描述 - 操作的描述。 - 參數 - 包含所需參數清單的陣列。 - render - 預設的自訂函數或字串。 - handler - 由操作觸發的可執行函數。 ``` useCopilotAction({ name: "sayHello", description: "Say hello to someone.", parameters: [ { name: "name", type: "string", description: "name of the person to say greet", }, ], render: "Process greeting message...", handler: async ({ name }) => { alert(`Hello, ${name}!`); }, }); ``` `useMakeCopilotReadable`掛鉤向 CopilotKit 提供應用程式狀態。 ``` import { useMakeCopilotReadable } from "@copilotkit/react-core"; const appState = ...; useMakeCopilotReadable(JSON.stringify(appState)); ``` CopilotKit 還允許您為使用者提示提供上下文,使其能夠做出充分且準確的決策。 將`guidance.ts`和`script.ts`加入到專案內的`lib`資料夾中,並將此[指導](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/lib/guideline.ts)和[腳本建議](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/lib/script.ts)複製到檔案中,以便 CopilotKit 做出決策。 在應用程式元件中,將當前日期、腳本建議和指導傳遞到 CopilotKit。 ``` import { GUIDELINE } from "@/lib/guideline"; import { SCRIPT_SUGGESTION } from "@/lib/script"; import { useCopilotAction, useMakeCopilotReadable, } from "@copilotkit/react-core"; export function App() { //-- 👉🏻 ...other component functions //👇🏻 Ground the Copilot with domain-specific knowledge for this use-case: marketing campaigns. useMakeCopilotReadable(GUIDELINE); useMakeCopilotReadable(SCRIPT_SUGGESTION); //👇🏻 Provide the Copilot with the current date. useMakeCopilotReadable("Today's date is " + new Date().toDateString()); return ( <div className='relative'> <CampaignForm segments={segments} currentCampaign={currentCampaign} setCurrentCampaign={setCurrentCampaign} saveCampaign={(campaign) => { if (campaign) { saveCampaign(campaign); } setCurrentCampaign(undefined); }} /> <Dashboard campaigns={campaigns} setCurrentCampaign={setCurrentCampaign} segments={segments} setSegments={setSegments} /> </div> ); } ``` 在`App`元件中建立一個 CopilotKit 操作,該操作可在使用者提供此類指令時建立新的活動或編輯現有的活動。 ``` useCopilotAction({ name: "updateCurrentCampaign", description: "Edit an existing campaign or create a new one. To update only a part of a campaign, provide the id of the campaign to edit and the new values only.", parameters: [ { name: "id", description: "The id of the campaign to edit. If empty, a new campaign will be created", type: "string", }, { name: "title", description: "The title of the campaign", type: "string", required: false, }, { name: "keywords", description: "Search keywords for the campaign", type: "string", required: false, }, { name: "url", description: "The URL to link the ad to. Most of the time, the user will provide this value, leave it empty unless asked by the user.", type: "string", required: false, }, { name: "headline", description: "The headline displayed in the ad. This should be a 5-10 words", type: "string", required: false, }, { name: "description", description: "The description displayed in the ad. This should be a short text", type: "string", required: false, }, { name: "budget", description: "The budget of the campaign", type: "number", required: false, }, { name: "objective", description: "The objective of the campaign", type: "string", enum: [ "brand-awareness", "lead-generation", "sales-conversion", "website-traffic", "engagement", ], }, { name: "bidStrategy", description: "The bid strategy of the campaign", type: "string", enum: ["manual-cpc", "cpa", "cpm"], required: false, }, { name: "bidAmount", description: "The bid amount of the campaign", type: "number", required: false, }, { name: "segment", description: "The segment of the campaign", type: "string", required: false, enum: segments, }, ], handler: (campaign) => { const newValue = _.assign( _.cloneDeep(currentCampaign), _.omitBy(campaign, _.isUndefined) ) as Campaign; setCurrentCampaign(newValue); }, render: (props) => { if (props.status === "complete") { return "Campaign updated successfully"; } else { return "Updating campaign"; } }, }); ``` {% 嵌入 https://www.youtube.com/watch?v=gCJpH6Tnj5g %} 新增另一個模擬 API 呼叫的操作,以允許 CopilotKit 從先前建立的活動中檢索歷史資料。 ``` // Provide this component's Copilot with the ability to retrieve historical cost data for certain keywords. // Will be called automatically when needed by the Copilot. useCopilotAction({ name: "retrieveHistoricalData", description: "Retrieve historical data for certain keywords", parameters: [ { name: "keywords", description: "The keywords to retrieve data for", type: "string", }, { name: "type", description: "The type of data to retrieve for the keywords.", type: "string", enum: ["CPM", "CPA", "CPC"], }, ], handler: async ({ type }) => { // fake an API call that retrieves historical data for cost for certain keywords based on campaign type (CPM, CPA, CPC) await new Promise((resolve) => setTimeout(resolve, 2000)); function getRandomValue(min: number, max: number) { return (Math.random() * (max - min) + min).toFixed(2); } if (type == "CPM") { return getRandomValue(0.5, 10); } else if (type == "CPA") { return getRandomValue(5, 100); } else if (type == "CPC") { return getRandomValue(0.2, 2); } }, render: (props) => { // Custom in-chat component rendering. Different components can be rendered based on the status of the action. let label = "Retrieving historical data ..."; if (props.args.type) { label = `Retrieving ${props.args.type} for keywords ...`; } if (props.status === "complete") { label = `Done retrieving ${props.args.type} for keywords.`; } const done = props.status === "complete"; return ( <div className=''> <div className=' w-full relative max-w-xs'> <div className='absolute inset-0 h-full w-full bg-gradient-to-r from-blue-500 to-teal-500 transform scale-[0.80] bg-red-500 rounded-full blur-3xl' /> <div className='relative shadow-xl bg-gray-900 border border-gray-800 px-4 py-8 h-full overflow-hidden rounded-2xl flex flex-col justify-end items-start'> <h1 className='font-bold text-sm text-white mb-4 relative z-50'> {label} </h1> <p className='font-normal text-base text-teal-200 mb-2 relative z-50 whitespace-pre'> {props.args.type && `Historical ${props.args.type}: ${props.result || "..."}`} </p> </div> </div> </div> ); }, }); ``` ![應用程式預覽](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kz3xm63ciq5q3kyooz9s.gif) 恭喜!您已完成本教學的專案。 結論 -- [CopilotKit](https://copilotkit.ai/)是一款令人難以置信的工具,可讓您在幾分鐘內將 AI Copilot 加入到您的產品中。無論您是對人工智慧聊天機器人和助理感興趣,還是對複雜任務的自動化感興趣,CopilotKit 都能讓您輕鬆實現。 如果您需要建立 AI 產品或將 AI 工具整合到您的軟體應用程式中,您應該考慮 CopilotKit。 您可以在 GitHub 上找到本教學的源程式碼: <https://github.com/CopilotKit/campaign-manager-demo> 感謝您的閱讀! --- 原文出處:https://dev.to/copilotkit/build-an-ai-powered-campaign-manager-nextjs-openai-copilotkit-59ii

我用新的程式語言微調了我的模型。你也可以做到! 🚀

我使用 OpenAI ChatGPT-4 一段時間了。 對此我沒什麼好說的。 但有時,這還不夠。 在[Winglang](https://github.com/winglang/wing)中,我們希望使用 OpenAI 和 ChatGPT-4 根據我們的文件回答人們的問題。 您的選擇是: - 使用[OpenAI 助理](https://platform.openai.com/docs/assistants/overview?context=with-streaming)或任何其他基於向量的資料庫 (RAG)。由於 Wing 看起來像 JS,所以效果很好,但仍然有很多錯誤。 - 將整個文件傳遞到上下文視窗的成本非常高。 很快,我們意識到這是行不通的。 是時候舉辦我們自己的法學碩士課程了。 ![問題](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o9x9ng6feh6x739djcb0.gif) --- 您的 LLM 資料集 ========== 在訓練模型之前,我們需要建立用於訓練模型的資料。在我們的例子中,是 Winglang 文件。我會做一些非常簡單的事情。 1. 從網站地圖中提取所有 URL,設定 GET 請求並收集內容。 2. 解析它;我們希望將所有 HTML 轉換為可讀內容。 3. 使用 ChatGPT 4 執行它,將內容轉換為 CSV 作為資料集。 它應該是這樣的: ![法學碩士資料集](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e2xq8lm4b31k8pop4gmc.png) 完成後,儲存包含一列名為`text`的 CSV 並新增問題和答案。我們稍後會用到它。它應該看起來像這樣: ``` text <s>[INST]How to define a variable in Winglang[/INST] let a = 'Hello';</s> <s>[INST]How to create a new lambda[/INST] bring cloud; let func = new cloud.Function(inflight () => { log('Hello from the cloud!'); });</s> ``` 將其保存在電腦上名為`data`新資料夾中。 --- Autotrain,您的模型 ============== 我的電腦很弱,所以我決定使用更小的模型 - 7b 參數: `mistralai/Mistral-7B-v0.1` 訓練模型的方法有數百萬種。我們將使用 Huggingface Autotrain。我們將使用他們的 CLI,而不執行任何 Python 程式碼🚀 當您使用 Huggingface 的 Autotrain 時,您可以在電腦上訓練它(這裡是我的方法)或在他們的伺服器上訓練它(付費)並訓練更大的模型。 我的舊 Macbook Pro M1 2021 沒有 GPU。 讓我們安裝自動訓練。 ``` pip install -U autotrain-advanced autotrain setup > setup_logs.txt ``` 然後,我們需要做的就是執行 autotrain 指令: ``` autotrain llm \ --train \ --model "mistralai/Mistral-7B-Instruct-v0.2" \ --project-name "autotrain-wing" \ --data-path data/ \ --text-column text \ --lr "0.0002" \ --batch-size "1" \ --epochs "3" \ --block-size "1024" \ --warmup-ratio "0.1" \ --lora-r "16" \ --lora-alpha "32" \ --lora-dropout "0.05" \ --weight-decay "0.01" \ --gradient-accumulation "4" \ --quantization "int4" \ --mixed-precision "fp16" \ --peft ``` 完成後,您將擁有一個名為“autotrain-wing”的新目錄,其中包含新的微調模型🚀 --- 玩模型 --- 要使用模型,請先執行: ``` pip install transformers torch ``` 完成後,使用以下程式碼建立一個名為 invoke.py 的新 Python 檔案: ``` from transformers import pipeline # Path to your local model directory model_path = "./autotrain-wing" # Load the model and tokenizer from the local directory classifier = pipeline("text-classification", model=model_path, tokenizer=model_path) # Example text to classify text = "Example text to classify" result = classifier(text) print(result) ``` 然後您可以透過執行 CLI 命令來執行它: ``` python invoke.py ``` 你就完成了🚀 --- 繼續攻讀法學碩士 -------- 我仍在學習法學碩士。 我意識到的一件事是追蹤模型的變化並不容易。 你不能真正將它與 Git 一起使用,因為模型可以達到非常大的大小 &gt; 100 GB;這沒有多大意義——git 不能很好地處理它。 更好的方法是使用名為[KitOps 的](https://github.com/jozu-ai/kitops/)工具。 我認為它很快就會成為法學碩士世界的標準,所以請確保你給這個庫加註星標,以便以後可以使用它。 1. 下載最新的[KitOps 版本](https://github.com/jozu-ai/kitops/releases/tag/v0.1.3)並[安裝它](https://kitops.ml/docs/cli/installation.html)。 2. 轉到模型資料夾並執行命令來打包您的 LLM: ``` kit pack . ``` 3. 您也可以透過執行將其推送到 Docker hub ``` kit pack . -t [your registry address]/[your repository name]/mymodelkit:latest ``` > 💡 要了解如何使用 DockerHub,[請檢查此](https://kitops.ml/docs/quick-start.html) {% cta https://github.com/jozu-ai/kitops %}⭐️ Star KitOps,以便您稍後可以再次找到它⭐️{% endcta %} [![星庫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/362tc5831i5ozbsau2o3.png)](https://github.com/jozu-ai/kitops) --- 我建立了一個新的 YouTube 頻道,主要是關於開源行銷:) (例如如何獲得星星、叉子和客戶端) 如果您對此感興趣,請隨時在這裡訂閱: https://www.youtube.com/@nevo-david?sub\_confirmation=1 --- 原文出處:https://dev.to/github20k/i-fine-tuned-my-model-on-a-new-programming-language-you-can-do-it-too-449

🚀 21 個將你的開發技能帶上月球的工具 🌝

我見過數百種人工智慧工具,其中許多正在改變世界。 作為開發人員,總是有很多事情需要學習,因此專注於節省時間來處理重要的事情非常重要。 我將介紹 21 個供開發人員使用的工具,它們可以讓您的生活更輕鬆,特別是在開發人員體驗方面。 相信我,這份清單會讓你大吃一驚! 我們開始做吧。 --- 1. [Taipy](https://github.com/Avaiga/taipy) - 將資料和人工智慧演算法整合到生產就緒的 Web 應用程式中。 ---------------------------------------------------------------------------- ![打字](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wd10iiofzmt4or4db6ej.png) Taipy 是一個開源 Python 庫,可用於輕鬆的端到端應用程式開發,具有假設分析、智慧管道執行、內建調度和部署工具。 我相信你們大多數人都不明白 Taipy 用於為基於 Python 的應用程式建立 GUI 介面並改進資料流管理。 關鍵是性能,而 Taipy 是最佳選擇。 雖然 Streamlit 是一種流行的工具,但在處理大型資料集時,其效能可能會顯著下降,這使得它在生產級使用上不切實際。 另一方面,Taipy 在不犧牲性能的情況下提供了簡單性和易用性。透過嘗試 Taipy,您將親身體驗其用戶友好的介面和高效的資料處理。 ![大資料支持](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xnvk0tozn0lgj083rzcb.gif) Taipy 有許多整合選項,可以輕鬆地與領先的資料平台連接。 ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7yv31uir3erina587zp8.png) 開始使用以下命令。 ``` pip install taipy ``` 我們來談談最新的[Taipy v3.1 版本](https://docs.taipy.io/en/latest/relnotes/)。 最新版本使得在 Taipy 的多功能零件物件中可視化任何 HTML 或 Python 物件成為可能。 這意味著[Folium](https://python-visualization.github.io/folium/latest/) 、 [Bokeh](https://bokeh.org/) 、 [Vega-Altair](https://altair-viz.github.io/)和[Matplotlib](https://matplotlib.org/)等程式庫現在可用於視覺化。 這也帶來了對[Plotly python](https://plotly.com/python/)的原生支持,使繪製圖表變得更加容易。 他們還使用分散式運算提高了效能,但最好的部分是 Taipy,它的所有依賴項現在都與 Python 3.12 完全相容,因此您可以在使用 Taipy 進行專案的同時使用最新的工具和程式庫。 您可以閱讀[文件](https://docs.taipy.io/en/latest/)。 ![用例](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdvnbejf9aivxmqsd3hx.png) 另一個有用的事情是,Taipy 團隊提供了一個名為[Taipy Studio](https://docs.taipy.io/en/latest/manuals/studio/)的 VSCode 擴充功能來加速 Taipy 應用程式的建置。 ![太皮工作室](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kc1umm5hcxes0ydbuspb.png) 您也可以使用 Taipy 雲端部署應用程式。 如果您想閱讀部落格來了解程式碼庫結構,您可以閱讀 HuggingFace[的使用 Taipy 在 Python 中為您的 LLM 建立 Web 介面](https://huggingface.co/blog/Alex1337/create-a-web-interface-for-your-llm-in-python)。 嘗試新技術通常很困難,但 Taipy 提供了[10 多個演示教程,](https://docs.taipy.io/en/release-3.1/gallery/)其中包含程式碼和適當的文件供您遵循。 ![示範](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4wigid2aokt6spkkoivr.png) 例如,一些演示範例和專案想法: - [即時污染儀表板](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/pollution_sensors/) 使用工廠周圍的感測器測量空氣品質的用例,展示 Taipy 儀表板流資料的能力。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-realtime-pollution)。 - [詐欺辨識](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/fraud_detection/) Taipy 應用程式可分析信用卡交易以偵測詐欺行為。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-fraud-detection)。 - [新冠儀表板](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/covid_dashboard/) 這使用 2020 年的 Covid 資料集。還有一個預測頁面來預測傷亡人數。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-covid-dashboard)。 - [建立 LLM 聊天機器人](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/chatbot/) 該演示展示了 Taipy 使最終用戶能夠使用 LLM 執行推理的能力。在這裡,我們使用 GPT-3 建立一個聊天機器人,並將對話顯示在互動式聊天介面中。您可以輕鬆更改程式碼以使用任何其他 API 或模型。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-chatbot)。 - [即時人臉辨識](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/face_recognition/) 該演示將人臉辨識無縫整合到我們的平台中,使用網路攝影機提供使用者友好的即時人臉偵測體驗。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-face-recognition)。 這些用例非常驚人,所以一定要檢查一下。 Taipy 在 GitHub 上有 8.2k+ Stars,並且處於`v3.1`版本,因此它們正在不斷改進。 {% cta https://github.com/Avaiga/taipy %} Star Taipy ⭐️ {% endcta %} --- 2. [DevToys](https://github.com/DevToys-app/DevToys) - 開發者的瑞士軍刀。 ---------------------------------------------------------------- ![開發玩具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7zfl1wjr01fdvca6wxbi.png) DevToys 協助完成日常開發任務,例如格式化 JSON、比較文字和測試 RegExp。 這樣,就無需使用不可信的網站來處理您的資料執行簡單的任務。透過智慧型偵測,DevToys 可以偵測用於複製到 Windows 剪貼簿的資料的最佳工具。 緊湊的覆蓋範圍讓您可以保持應用程式較小並位於其他視窗之上。最好的部分是可以同時使用應用程式的多個實例。 我可以肯定地說,開發人員甚至不知道這個很棒的專案。 最後是一款專為 Windows 生態系統設計的軟體。哈哈! ![工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7wd60jsgdb5tx2t2adi.png) 他們提供的一些工具是: > 轉換器 - JSON &lt;&gt; YAML - 時間戳 - 數基數 - 規劃任務解析器 ![轉換器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g8x784fx53x6ia02zal0.png) > 編碼器/解碼器 - 超文本標記語言 - 網址 - Base64 文字與圖片 - 壓縮包 - 智威湯遜解碼器 ![編碼器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/73ts4x1vtcy4yswsmytw.png) > 格式化程式 - JSON - SQL - XML ![XML](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e5dc8ko2baywta82ymq5.png) > 發電機 - 哈希(MD5、SHA1、SHA256、SHA512) - UUID 1 和 4 - 洛雷姆·伊普蘇姆 - 校驗和 ![發電機](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cwsq8xig6jf69wr99iuv.png) > 文字 - 逃脫/逃脫 - 檢驗員和箱子轉換器 - 正規表示式測試器 - 文字比較 - XML驗證器 - 降價預覽 ![MD預覽](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vcbkse1i5324qg3xu1yd.png) ![文字差異](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hlqqib4fcjimc03pdrwr.png) > 形象的 - 色盲模擬器 - 顏色選擇器和對比度 - PNG / JPEG 壓縮器 - 影像轉換器 ![圖形工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/631upekcqzh62xyrdjwt.png) 我不了解你,但我不會錯過這個! 您可以閱讀[如何執行 DevToys](https://github.com/DevToys-app/DevToys?tab=readme-ov-file#how-to-run-devtoys) 。 關於許可證的註解。 DevToys 使用的授權允許將應用程式作為試用軟體或共享軟體重新分發而無需進行任何更改。然而,作者 Etienne BAUDOUX 和 BenjaminT 不希望你這樣做。如果您認為自己有充分的理由這樣做,請先與我們聯絡討論。 他們在 GitHub 上有 23k Stars,並且使用 C#。 {% cta https://github.com/DevToys-app/DevToys %} 明星 DevToys ⭐️ {% endcta %} --- 3. [Pieces](https://github.com/pieces-app) - 您的工作流程副駕駛。 ------------------------------------------------------- ![件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qf2qgqtpv78fxw5guqm5.png) Pieces 是一款支援人工智慧的生產力工具,旨在透過智慧程式碼片段管理、情境化副駕駛互動和主動呈現有用材料來幫助開發人員管理混亂的工作流程。 它最大限度地減少了上下文切換、簡化了工作流程並提升了整體開發體驗,同時透過完全離線的 AI 方法維護了工作的隱私和安全性。太棒了:D ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2ro3rcwnqp4qrmv5e8s.png) 它與您最喜歡的工具無縫集成,以簡化、理解和提升您的編碼流程。 它具有比表面上看到的更令人興奮的功能。 - 它可以透過閃電般快速的搜尋體驗找到您需要的材料,讓您根據您的喜好透過自然語言、程式碼、標籤和其他語義進行查詢。可以放心地說“您的個人離線谷歌”。 - Pieces 使用 OCR 和 Edge-ML 升級螢幕截圖,以提取程式碼並修復無效字元。因此,您可以獲得極其準確的程式碼提取和深度元資料豐富。 您可以查看 Pieces 可用[功能的完整清單](https://pieces.app/features)。 您可以閱讀[文件](https://docs.pieces.app/)並存取[網站](https://pieces.app/)。 他們為 Pieces OS 用戶端提供了一系列 SDK 選項,包括[TypeScript](https://github.com/pieces-app/pieces-os-client-sdk-for-typescript) 、 [Kotlin](https://github.com/pieces-app/pieces-os-client-sdk-for-kotlin) 、 [Python](https://github.com/pieces-app/pieces-os-client-sdk-for-python)和[Dart](https://github.com/pieces-app/pieces-os-client-sdk-for-dart) 。 就開源流行度而言,他們仍然是新的,但他們的社群是迄今為止我見過的最好的社群之一。加入他們,成為 Pieces 的一部分! {% cta https://github.com/pieces-app/ %} 星星碎片 ⭐️ {% endcta %} --- 4. [Infisical-](https://github.com/Infisical/infisical)秘密管理平台。 -------------------------------------------------------------- ![內部的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jrolzjdnkky1r694h9av.png) Infisical 是一個開源秘密管理平台,團隊可以用它來集中 API 金鑰、資料庫憑證和設定等秘密。 他們讓每個人(而不僅僅是安全團隊)都可以更輕鬆地進行秘密管理,這意味著從頭開始重新設計整個開發人員體驗。 就我個人而言,我不介意使用 .env 文件,因為我並不特別謹慎。不過,您可以閱讀[立即停止使用 .env 檔案!](https://dev.to/gregorygaines/stop-using-env-files-now-kp0)由格雷戈里來理解。 他們提供了四種 SDK,分別用於<a href="">Node.js</a> 、 <a href="">Python</a> 、 <a href="">Java</a>和<a href="">.Net</a> 。您可以自行託管或使用他們的雲端。 開始使用以下 npm 指令。 ``` npm install @infisical/sdk ``` 這是使用入門 (Node.js SDK) 的方法。 ``` import { InfisicalClient, LogLevel } from "@infisical/sdk"; const client = new InfisicalClient({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", logLevel: LogLevel.Error }); const secrets = await client.listSecrets({ environment: "dev", projectId: "PROJECT_ID", path: "/foo/bar/", includeImports: false }); ``` ![內部](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h3eu288l470du91b66pd.png) Infisical 還提供了一組工具來自動防止 git 歷史記錄的秘密洩露。可以使用預提交掛鉤或透過與 GitHub 等平台直接整合在 Infisical CLI 層級上設定此功能。 您可以閱讀[文件](https://infisical.com/docs/documentation/getting-started/introduction)並檢查如何[安裝 CLI](https://infisical.com/docs/cli/overview) ,這是使用它的最佳方式。 Infisical 還可用於將機密注入 Kubernetes 叢集和自動部署,以便應用程式使用最新的機密。有很多整合選項可用。 ![內部](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5x0tvt5ycaiqhggv6wml.png) 在使用整個原始程式碼之前一定要檢查他們的[許可證](https://github.com/Infisical/infisical/blob/main/LICENSE),因為他們有一些受 MIT Expat 保護的企業級程式碼,但不用擔心,大部分程式碼都是免費使用的。 他們在 GitHub 上擁有超過 11k 顆星星,並且發布了超過 125 個版本,因此他們正在不斷發展。另外,Infiscial CLI 的安裝次數超過 540 萬次,因此非常值得信賴。 {% cta https://github.com/Infisical/infisical %} 明星 Infisical ⭐️ {% endcta %} --- 5. [Mintlify](https://github.com/mintlify/writer) - 在建置時出現的文件。 -------------------------------------------------------------- ![精簡](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gvk07kmn8p48cpssogov.png) Mintlify 是一款由人工智慧驅動的文件編寫器,您只需 1 秒鐘即可編寫程式碼文件 :D 幾個月前我發現了 Mintlify,從那時起我就一直是它的粉絲。我見過很多公司使用它,甚至我使用我的商務電子郵件產生了完整的文件,結果證明這是非常簡單和體面的。如果您需要詳細的文件,Mintlify 就是解決方案。 主要用例是根據我們將在此處討論的程式碼產生文件。當您編寫程式碼時,它會自動記錄程式碼,以便其他人更容易跟上。 您可以安裝[VSCode 擴充功能](https://marketplace.visualstudio.com/items?itemName=mintlify.document)或將其安裝在[IntelliJ](https://plugins.jetbrains.com/plugin/18606-mintlify-doc-writer)上。 您只需突出顯示程式碼或將遊標放在要記錄的行上。然後點選「編寫文件」按鈕(或按 ⌘ + 。) 您可以閱讀[文件](https://github.com/mintlify/writer?tab=readme-ov-file#%EF%B8%8F-mintlify-writer)和[安全指南](https://writer.mintlify.com/security)。 如果您更喜歡教程,那麼您可以觀看[Mintlify 的工作原理](https://www.loom.com/embed/3dbfcd7e0e1b47519d957746e05bf0f4)。它支援 10 多種程式語言,並支援許多文件字串格式,例如 JSDoc、reST、NumPy 等。 順便說一句,他們的網站連結是[writer.mintlify.com](https://writer.mintlify.com/) ;回購協議中目前的似乎是錯誤的。 Mintlify 是一個方便的工具,用於記錄程式碼,這是每個開發人員都應該做的事情。它使其他人更容易有效地理解您的程式碼。 它在 GitHub 上有大約 2.5k 顆星,基於 TypeScript 建置,受到許多開發人員的喜愛。 {% cta https://github.com/mintlify/writer %} Star Mintlify ⭐️ {% endcta %} --- 6. [Replexica](https://github.com/replexica/replexica) - 用於 React 的 AI 支援的 i18n 工具包。 ------------------------------------------------------------------------------------ ![反射](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/htgshukxy927iy37ui33.png) 在地化方面的困難是真實存在的,因此人工智慧的幫助絕對是一個很酷的概念。 Replexica 是 React 的 i18n 工具包,可快速發布多語言應用程式。它不需要將文字提取到 JSON 檔案中,並使用 AI 支援的 API 進行內容處理。 它有以下兩個部分: 1. Replexica Compiler - React 的開源編譯器插件。 2. Replexica API - 雲端中的 i18n API,使用 LLM 執行翻譯。 (基於使用情況,它有免費套餐) 支援的一些 i18n 格式包括: 1. 無 JSON 的 Replexica 編譯器格式。 2. Markdown 內容的 .md 檔案。 3. 基於舊版 JSON 和 YAML 的格式。 當他們達到 500 星時,他們也在 DEV 上發布了官方公告。我是第一批讀者之一(少於 3 個反應)。 它們涵蓋了很多內容,因此您應該閱讀 Max 的[《We Got 500 Stars What Next》](https://dev.to/maxprilutskiy/we-got-500-github-stars-whats-next-2njc) 。 為了給出 Replexica 背後的總體思路,這是基本 Next.js 應用程式所需的唯一更改,以使其支援多語言。 開始使用以下 npm 指令。 ``` // install pnpm add replexica @replexica/react @replexica/compiler // login to Replexica API. pnpm replexica auth --login ``` 您可以這樣使用它。 ``` // next.config.mjs // Import Replexica Compiler import replexica from '@replexica/compiler'; /** @type {import('next').NextConfig} */ const nextConfig = {}; // Define Replexica configuration /** @type {import('@replexica/compiler').ReplexicaConfig} */ const replexicaConfig = { locale: { source: 'en', targets: ['es'], }, }; // Wrap Next.js config with Replexica Compiler export default replexica.next( replexicaConfig, nextConfig, ); ``` 您可以閱讀如何[開始使用](https://github.com/replexica/replexica/blob/main/getting-started.md)以及清楚記錄的有關[幕後使用內容的](https://github.com/replexica/replexica?tab=readme-ov-file#whats-under-the-hood)內容。 Replexica 編譯器支援 Next.js App Router,Replexica API 支援英文🇺🇸和西班牙文🇪🇸。他們計劃接下來發布 Next.js Pages Router + 法語🇫🇷語言支援! 他們在 GitHub 上擁有 740 多個 Star,並且基於 TypeScript 建置。您應該密切關注該專案以獲得進一步進展! {% cta https://github.com/replexica/replexica %} Star Replexica ⭐️ {% endcta %} --- 7. [Flowise](https://github.com/FlowiseAI/Flowise) - 拖放 UI 來建立您的客製化 LLM 流程。 --------------------------------------------------------------------------- ![弗洛伊薩伊](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r5bp43nil764fhe4a05z.png) Flowise 是一款開源 UI 視覺化工具,用於建立客製化的 LLM 編排流程和 AI 代理程式。 開始使用以下 npm 指令。 ``` npm install -g flowise npx flowise start OR npx flowise start --FLOWISE_USERNAME=user --FLOWISE_PASSWORD=1234 ``` 這就是整合 API 的方式。 ``` import requests url = "/api/v1/prediction/:id" def query(payload): response = requests.post( url, json = payload ) return response.json() output = query({ question: "hello!" )} ``` ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ahk2ovjrpq1qk3r5pfot.png) 您可以閱讀[文件](https://docs.flowiseai.com/)。 ![流程化人工智慧](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trkltpn5lk1y1pte0smd.png) 雲端主機不可用,因此您必須使用這些[說明](https://github.com/FlowiseAI/Flowise?tab=readme-ov-file#-self-host)自行託管。 讓我們探討一些用例: - 假設您有一個網站(可以是商店、電子商務網站或部落格),並且您希望廢棄該網站的所有相關連結,並讓法學碩士回答您網站上的任何問題。您可以按照此[逐步教學](https://docs.flowiseai.com/use-cases/web-scrape-qna)來了解如何實現相同的目標。 ![刮刀](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e91sz2mga5wvc0x2hp2g.png) - 您還可以建立一個自訂工具,該工具將能夠呼叫 Webhook 端點並將必要的參數傳遞到 Webhook 主體中。請依照本[指南](https://docs.flowiseai.com/use-cases/webhook-tool)使用 Make.com 建立 Webhook 工作流程。 ![網路鉤子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ckyivo9dvue461jc9pv4.png) 還有許多其他用例,例如建立 SQL QnA 或與 API 互動。 FlowiseAI 在 GitHub 上擁有超過 27,500 個 Star,並擁有超過 10,000 個分叉,因此具有良好的整體比率。 {% cta https://github.com/FlowiseAI/Flowise %} 明星 Flowise ⭐️ {% endcta %} --- 8. [Hexo](https://github.com/hexojs/hexo) - 一個快速、簡單且功能強大的部落格框架。 --------------------------------------------------------------- ![六角形](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6vos07fyydiupqqplo2s.png) 大多數開發人員更喜歡自己的博客,如果您也是如此。 Hexo 可能是你不知道的工具。 Hexo 支援許多功能,例如超快的生成速度,支援 GitHub Flavored Markdown 和大多數 Octopress 插件,提供對 GitHub Pages、Heroku 等的一命令部署,以及可實現無限擴展性的強大 API 和數百個主題和插件。 這意味著您可以用 Markdown(或其他標記語言)編寫帖子,Hexo 在幾秒鐘內生成具有漂亮主題的靜態檔案。 開始使用以下 npm 指令。 ``` npm install hexo-cli -g ``` 您可以這樣使用它。 ``` // Setup your blog hexo init blog // Start the server hexo server // Create a new post hexo new "Hello Hexo" ``` 您可以閱讀[文件](https://hexo.io/docs/),查看 Hexo 提供的所有[400 多個外掛程式](https://hexo.io/plugins/)和[主題集](https://hexo.io/themes/)。據我所知,這些外掛程式支援廣泛的用例,例如 Hexo 的 Ansible 部署器外掛程式。 您可以查看有關在[Hexo 上編寫和組織內容的](https://www.youtube.com/watch?v=AIqBubK6ZLc&t=6s)YouTube 教學。 Hexo 在 GitHub 上擁有超過 38,000 顆星,並被 GitHub 上超過 125,000 名開發者使用。它們位於`v7`版本中,解壓縮後大小為`629 kB` 。 {% cta https://github.com/hexojs/hexo %} Star Hexo ⭐️ {% endcta %} --- 9.[螢幕截圖到程式碼](https://github.com/abi/screenshot-to-code)- 放入螢幕截圖並將其轉換為乾淨的程式碼。 --------------------------------------------------------------------------- ![截圖到程式碼](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5akiyz5telxqqsj32ftu.png) 這個開源專案廣泛流行,但許多開發人員仍然不了解它。它可以幫助您以 10 倍的速度建立使用者介面。 這是一個簡單的工具,可以使用 AI 將螢幕截圖、模型和 Figma 設計轉換為乾淨、實用的程式碼。 該應用程式有一個 React/Vite 前端和一個 FastAPI 後端。如果您想使用 Claude Sonnet 或獲得實驗視訊支持,您將需要一個能夠存取 GPT-4 Vision API 的 OpenAI API 金鑰或一個 Anthropic 金鑰。您可以閱讀[指南](https://github.com/abi/screenshot-to-code?tab=readme-ov-file#-getting-started)來開始。 您可以在託管版本上[即時試用](https://screenshottocode.com/),並觀看 wiki 上提供的[一系列演示影片](https://github.com/abi/screenshot-to-code/wiki/Screen-Recording-to-Code)。 他們在 GitHub 上擁有超過 47k 顆星星,並支援許多技術堆疊,例如 React 和 Vue,以及不錯的 AI 模型,例如 GPT-4 Vision、Claude 3 Sonnet 和 DALL-E 3。 {% cta https://github.com/abi/screenshot-to-code %} 將螢幕截圖轉為程式碼 ⭐️ {% endcta %} --- 10. [Appsmith](https://github.com/appsmithorg/appsmith) - 建立管理面板、內部工具和儀表板的平台。 ----------------------------------------------------------------------------- ![應用史密斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rt7s0r3wz2leec83cl17.png) 管理面板和儀表板是任何軟體創意(在大多數情況下)的一些常見部分,我嘗試從頭開始建立它,這會帶來很多痛苦和不必要的辛苦工作。 您可能已經看到組織建立了內部應用程式,例如儀表板、資料庫 GUI、管理面板、批准應用程式、客戶支援儀表板等,以幫助其團隊執行日常操作。正如我所說,Appsmith 是一個開源工具,可以實現這些內部應用程式的快速開發。 首先,請觀看這個[YouTube 影片](https://www.youtube.com/watch?v=NnaJdA1A11s),該影片在 100 秒內解釋了 Appsmith。 {% 嵌入 https://www.youtube.com/watch?v=NnaJdA1A11s %} 他們提供拖放小部件來建立 UI。 您可以使用 45 多個可自訂的小工具在幾分鐘內建立漂亮的響應式 UI,而無需編寫一行 HTML/CSS。尋找[小部件的完整清單](https://www.appsmith.com/widgets)。 ![按鈕點擊小工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqpnnslvsvjl4gifseon.png) ![驗證](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/489fly7tvknz2uv2mgei.png) Appsmith 幾乎可以在 GUI 上的小部件屬性、事件偵聽器、查詢和其他設定內的任何位置編寫 JavaScript 程式碼。 Appsmith 支援在`{{ }}`內編寫單行程式碼,並將括號之間編寫的任何內容解釋為 JavaScript 表達式。 ``` /*Filter the data array received from a query*/ {{ QueryName.data.filter((row) => row.id > 5 ) }} or {{ storeValue("userID", 42); console.log(appsmith.store.userID); showAlert("userID saved"); }} ``` 您需要使用立即呼叫函數表達式(IIFE)來編寫多行。 例如,無效程式碼和有效程式碼。 ``` // invalid code /*Call a query to fetch the results and filter the data*/ {{ const array = QueryName.data; const filterArray = array.filter((row) => row.id > 5); return filterArray; }} /* Check the selected option and return the value*/ {{ if (Dropdown.selectedOptionValue === "1") { return "Option 1"; } else { return "Option 2"; } }} // valid code /* Call a query and then manipulate its result */ {{ (function() { const array = QueryName.data; const filterArray = array.filter((row) => row.id > 5); return filterArray; })() }} /* Verify the selected option and return the value*/ {{ (function() { if (Dropdown.selectedOptionValue === "1") { return "Option 1"; } else { return "Option 2"; } })() }} ``` 您可以透過幾個簡單的步驟建立從簡單的 CRUD 應用程式到複雜的多步驟工作流程的任何內容: 1. 與資料庫或 API 整合。 Appsmith 支援最受歡迎的資料庫和 REST API。 2. 使用內建小工具建立您的應用程式佈局。 3. 在編輯器中的任何位置使用查詢和 JavaScript 來表達您的業務邏輯。 4. Appsmith 支援使用 Git 進行版本控制,以使用分支來協作建立應用程式來追蹤和回滾變更。部署應用程式並分享:) ![應用史密斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yltcrmuzwdoydrwyqjpp.png) 您可以閱讀[文件](https://docs.appsmith.com/)和[操作指南](https://docs.appsmith.com/connect-data/how-to-guides),例如如何將其連接到本機資料來源或\[如何與第三方工具整合\](與第三方工具整合)。 您可以自行託管或使用雲端。他們還提供[20 多個模板](https://www.appsmith.com/templates),以便您可以快速入門。一些有用的是: - [維修訂單管理](https://www.appsmith.com/template/Maintenance-Order-Management) - [加密即時追蹤器](https://www.appsmith.com/template/crypto-live-tracker) - [內容管理系統](https://www.appsmith.com/template/content-management-system) - [WhatsApp 信使](https://www.appsmith.com/template/whatsapp-messenger) Appsmith 在 GitHub 上擁有超過 31,000 顆星,發布了 200 多個版本。 {% cta https://github.com/appsmithorg/appsmith %} Star Appsmith ⭐️ {% endcta %} --- 11. [BlockNote](https://github.com/TypeCellOS/BlockNote) - 基於區塊(Notion 樣式)且可擴充的富文本編輯器。 -------------------------------------------------------------------------------------- ![區塊註釋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eddx8cld0g492w3a8fjh.png) 人們常說,除非您正在學習新東西,否則不要重新發明輪子。 Blocknote 是開源的 Block 為基礎的 React 富文本編輯器。您可以輕鬆地將現代文字編輯體驗加入到您的應用程式中。 Blocknote 建構在 Prosemirror 和 Tiptap 之上。 它們有很多功能,如下所示。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h9kd6xnkg9fa5j29frot.png) ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezuz7ywh6vefixmpeyzk.png) 您可以輕鬆自訂內建 UI 元件,或建立自訂區塊、內聯內容和樣式。如果您想更進一步,您可以使用額外的 Prosemirror 或 TipTap 外掛程式來擴充核心編輯器。 其他庫雖然功能強大,但通常具有相當陡峭的學習曲線,並且要求您自訂編輯器的每個細節。這可能需要數月的專門工作。 相反,BlockNote 只需最少的設定即可提供出色的體驗,包括現成的動畫 UI。 開始使用以下 npm 指令。 ``` npm install @blocknote/core @blocknote/react ``` 您可以這樣使用它。透過`useCreateBlockNote`鉤子,我們可以建立一個新的編輯器實例,然後使用`theBlockNoteView`元件來渲染它。 `@blocknote/react/style.css`也被匯入來新增編輯器的預設樣式和 BlockNote 匯出的 Inter 字體(可選)。 ``` import "@blocknote/core/fonts/inter.css"; import { BlockNoteView, useCreateBlockNote } from "@blocknote/react"; import "@blocknote/react/style.css"; export default function App() { // Creates a new editor instance. const editor = useCreateBlockNote(); // Renders the editor instance using a React component. return <BlockNoteView editor={editor} />; } ``` 您可以閱讀可用的[文件](https://www.blocknotejs.org/docs)和[ui 元件](https://www.blocknotejs.org/docs/ui-components)。 您應該嘗試一下,特別是因為它包含廣泛的功能,例如「斜線」選單、流暢的動畫以及建立即時協作應用程式的潛力。 ![削減](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0i7ob8nrhpl7r70k6527.png) 斜線選單 ![即時協作](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/id22qol6y0838zgwad3y.png) 即時協作 ![格式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d8maems8tfhtehw9lkol.png) 格式選單 他們還提供了[20 多個範例](https://www.blocknotejs.org/examples)以及預覽和程式碼,您可以使用它們來快速跟進。 ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4uillknk0ogkcvpula7b.png) Blocknote 在 GitHub 上擁有超過 5,000 顆星,並有超過 1,500 名開發者在使用。 {% cta https://github.com/TypeCellOS/BlockNote %} 星 BlockNote ⭐️ {% endcta %} --- 12. [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 在數小時內為您的產品提供 AI Copilot。 ------------------------------------------------------------------------------------- ![副駕駛套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzuxjfog2ldam3csrl62.png) 將 AI 功能整合到 React 中是很困難的,這就是 Copilot 的用武之地。一個簡單快速的解決方案,可將可投入生產的 Copilot 整合到任何產品中! 您可以使用兩個 React 元件將關鍵 AI 功能整合到 React 應用程式中。它們還提供內建(完全可自訂)Copilot 原生 UX 元件,例如`<CopilotKit />` 、 `<CopilotPopup />` 、 `<CopilotSidebar />` 、 `<CopilotTextarea />` 。 開始使用以下 npm 指令。 ``` npm i @copilotkit/react-core @copilotkit/react-ui ``` Copilot Portal 是 CopilotKit 提供的元件之一,CopilotKit 是一個應用程式內人工智慧聊天機器人,可查看目前應用狀態並在應用程式內採取操作。它透過插件與應用程式前端和後端以及第三方服務進行通訊。 這就是整合聊天機器人的方法。 `CopilotKit`必須包裝與 CopilotKit 互動的所有元件。建議您也開始使用`CopilotSidebar` (您可以稍後切換到不同的 UI 提供者)。 ``` "use client"; import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import "@copilotkit/react-ui/styles.css"; export default function RootLayout({children}) { return ( <CopilotKit url="/path_to_copilotkit_endpoint/see_below"> <CopilotSidebar> {children} </CopilotSidebar> </CopilotKit> ); } ``` 您可以使用此[快速入門指南](https://docs.copilotkit.ai/getting-started/quickstart-backend)設定 Copilot 後端端點。 之後,您可以讓 Copilot 採取行動。您可以閱讀如何提供[外部上下文](https://docs.copilotkit.ai/getting-started/quickstart-chatbot#provide-context)。您可以使用`useMakeCopilotReadable`和`useMakeCopilotDocumentReadable`反應掛鉤來執行此操作。 ``` "use client"; import { useMakeCopilotActionable } from '@copilotkit/react-core'; // Let the copilot take action on behalf of the user. useMakeCopilotActionable( { name: "setEmployeesAsSelected", // no spaces allowed in the function name description: "Set the given employees as 'selected'", argumentAnnotations: [ { name: "employeeIds", type: "array", items: { type: "string" } description: "The IDs of employees to set as selected", required: true } ], implementation: async (employeeIds) => setEmployeesAsSelected(employeeIds), }, [] ); ``` 您可以閱讀[文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea)並查看[演示影片](https://github.com/CopilotKit/CopilotKit?tab=readme-ov-file#demo)。 您可以輕鬆整合 Vercel AI SDK、OpenAI API、Langchain 和其他 LLM 供應商。您可以按照本[指南](https://docs.copilotkit.ai/getting-started/quickstart-chatbot)將聊天機器人整合到您的應用程式中。 基本概念是在幾分鐘內建立可用於基於 LLM 的應用程式的 AI 聊天機器人。 用例是巨大的,作為開發人員,我們絕對應該在下一個專案中嘗試使用 CopilotKit。 CopilotKit 在 GitHub 上擁有超過 4,200 個星星,發布了 200 多個版本,這意味著它們正在不斷改進。 {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} --- 13.[自動完成](https://github.com/withfig/autocomplete)- IDE 風格的自動完成功能適用於您現有的終端和 shell。 ---------------------------------------------------------------------------------- ![自動完成](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8i8vcidsa023jf8r9382.png) [Fig](https://fig.io/?ref=github_autocomplete)讓命令列對個人來說更容易,對團隊來說更具協作性。 他們最受歡迎的產品是自動完成。當您鍵入時,Fig 會在現有終端機中彈出子命令、選項和上下文相關的參數。 最好的部分是您也可以將 Fig 的自動完成功能用於您自己的工具。以下是建立私人完成的方法: ``` import { ai } from "@fig/autocomplete-generators" ... generators: [ ai({ // the prompt prompt: "Generate a git commit message", // Send any relevant local context. message: async ({ executeShellCommand }) => { return executeShellCommand("git diff") }, //Turn each newline into a suggestion (can specify instead a `postProcess1 function if more flexibility is required) splitOn: "\n", }) ] ``` 您可以閱讀[Fig.io/docs](https://fig.io/docs/getting-started)了解如何開始。 他們在 GitHub 上有 24k+ Stars,這對於經常使用 shell 或終端機的開發人員來說非常有用。 {% cta https://github.com/withfig/autocomplete %} 星狀自動完成 ⭐️ {% endcta %} --- 14. [Tooljet](https://github.com/ToolJet/ToolJet) - 用於建立業務應用程式的低程式碼平台。 ---------------------------------------------------------------------- ![工具噴射器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xhipvjl2wnthjccgrpij.png) 我們都建立前端,但它通常非常複雜並且涉及很多因素。這樣可以省去很多麻煩。 ToolJet 是一個開源低程式碼框架,可以用最少的工程工作來建置和部署內部工具。 ToolJet 的拖放式前端建構器可讓您在幾分鐘內建立複雜的響應式前端。 您可以整合各種資料來源,包括PostgreSQL、MongoDB、Elasticsearch等資料庫;具有 OpenAPI 規範和 OAuth2 支援的 API 端點; SaaS 工具,例如 Stripe、Slack、Google Sheets、Airtable 和 Notion;以及 S3、GCS 和 Minio 等物件儲存服務來取得和寫入資料。一切 :) 這就是 Tooljet 的工作原理。 ![工具噴射器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r6vv09z7ioma1ce2ttei.png) 您可以在 ToolJet 中開發多步驟工作流程以自動化業務流程。除了建置和自動化工作流程之外,ToolJet 還可以在您的應用程式中輕鬆整合這些工作流程。 ![工作流程](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eh2vk3kih9fhck6okf67.png) 您可以閱讀此[快速入門指南](https://docs.tooljet.com/docs/getting-started/quickstart-guide),該指南向您展示如何使用 ToolJet 在幾分鐘內建立員工目錄應用程式。該應用程式將讓您透過漂亮的用戶介面追蹤和更新員工資訊。 查看可用[功能列表](https://github.com/ToolJet/ToolJet?tab=readme-ov-file#all-features),包括 45 多個內建響應式元件、50 多個資料來源等等。 您可以閱讀[文件](https://docs.tooljet.com/docs/)並查看[操作指南](https://docs.tooljet.com/docs/how-to/use-url-params-on-load)。 它們在 GitHub 上有 26k+ Stars,並且基於 JavaScript 建置。他們也獲得了 GitHub 的資助,從而建立了巨大的信任。 {% cta https://github.com/ToolJet/ToolJet %} Star ToolJet ⭐️ {% endcta %} --- 15. [Apitable](https://github.com/apitable/apitable) - 用於建立協作應用程式的 API 導向的低程式碼平台。 --------------------------------------------------------------------------------- ![有能力的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58syhvpb2fn6hhlyrtst.png) APITable 是一個面向 API 的低程式碼平台,用於建立協作應用程式,並表示它比所有其他 Airtable 開源替代品都要好。 有很多很酷的功能,例如: - 即時協作。 ![即時協作](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58kpvpab2nj92421yvy3.gif) - 您可以產生自動表單。 ![形式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0jo084gg0cd9xiud3nz3.gif) - 無限的跨錶連結。 ![交叉表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jnvb9sdp3uqrcn55hwug.gif) - API 第一個面板。 ![API第一個面板](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7u48ue4rl0q41rhh6bif.gif) - 強大的行/列功能。 ![行列](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/apxqwp84awdbj7cdw5yu.gif) 您可以閱讀完整的[功能清單](https://github.com/apitable/apitable?tab=readme-ov-file#-features)。 您可以嘗試[apitable](https://aitable.ai/)並在 apitable 的[live Gitpod demo](https://gitpod.io/#https://github.com/apitable/apitable)中查看該專案的演示。 您也可以閱讀[安裝指南](https://github.com/apitable/apitable?tab=readme-ov-file#installation),在本機或雲端運算環境中安裝 APITable。 {% cta https://github.com/apitable/apitable %} Star Apitable ⭐️ {% endcta %} --- 16. [n8n](https://github.com/n8n-io/n8n) - 工作流程自動化工具。 ----------------------------------------------------- ![n8n](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4pqsc84nhgj0b9dhfaxo.png) n8n 是一個可擴展的工作流程自動化工具。透過公平程式碼分發模型,n8n 將始終擁有可見的原始程式碼,可用於自託管,並允許您加入自訂函數、邏輯和應用程式。 每個開發人員都想使用的工具。自動化是生產力和簡單性的關鍵。 ![n8n](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxnp57kw5szbpj6mfs1p.png) n8n 基於節點的方法使其具有高度通用性,使您能夠將任何事物連接到任何事物。 有[400 多個集成選項](https://n8n.io/integrations),這幾乎是瘋狂的! 您可以看到所有[安裝](https://docs.n8n.io/choose-n8n/)選項,包括 Docker、npm 和自架。 開始使用以下命令。 ``` npx n8n ``` 此命令將下載啟動 n8n 所需的所有內容。然後,您可以透過開啟`http://localhost:5678`來存取 n8n 並開始建置工作流程。 在 YouTube 上觀看此[快速入門影片](https://www.youtube.com/watch?v=1MwSoB0gnM4)! {% 嵌入 https://www.youtube.com/watch?v=1MwSoB0gnM4 %} 您可以閱讀[文件](https://docs.n8n.io/)並閱讀本[指南](https://docs.n8n.io/try-it-out/),以便根據您的需求快速開始。 他們還提供初學者和中級[課程,](https://docs.n8n.io/courses/)以便輕鬆學習。 他們在 GitHub 上有 39k+ Stars,並提供兩個包供整體使用。 {% cta https://github.com/n8n-io/n8n %} 明星 n8n ⭐️ {% endcta %} --- 17. [DOMPurify](https://github.com/cure53/DOMPurify) - 一個僅限 DOM、超快、超級容忍 XSS 的 HTML 清理程式。 ---------------------------------------------------------------------------------------- ![DOM純化](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r846r2hmmw9d9wzvbocz.png) DOMPurify 是一款僅限 DOM、超快、超級容忍 XSS 的 HTML、MathML 和 SVG 清理工具。作為開發人員,我們的應用程式需要它來確保它們足夠安全。 DOMPurify 可以淨化 HTML 並防止 XSS 攻擊。 您可以向 DOMPurify 提供一個充滿髒 HTML 的字串,它將傳回一個包含乾淨 HTML 的字串(除非另有配置)。 DOMPurify 將刪除所有包含危險 HTML 的內容,從而防止 XSS 攻擊和其他惡意行為。這也太快了。 他們使用瀏覽器提供的技術並將其轉變為 XSS 過濾器。您的瀏覽器速度越快,DOMPurify 的速度就越快。 DOMPurify 使用 JavaScript 編寫,適用於所有現代瀏覽器(Safari (10+)、Opera (15+)、Edge、Firefox 和 Chrome - 以及幾乎所有使用 Blink、Gecko 或 WebKit 的其他瀏覽器)。它不會在 MSIE 或其他舊版瀏覽器上中斷。它根本什麼都不做。 開始使用以下 npm 指令。 ``` npm install dompurify npm install jsdom // or use the unminified development version <script type="text/javascript" src="src/purify.js"></script> ``` 您可以這樣使用它。 ``` const createDOMPurify = require('dompurify'); const { JSDOM } = require('jsdom'); const window = new JSDOM('').window; const DOMPurify = createDOMPurify(window); const clean = DOMPurify.sanitize('<b>hello there</b>'); ``` 如果您遇到問題,請參閱[文件](https://github.com/cure53/DOMPurify?tab=readme-ov-file#how-do-i-use-it)。他們已經記錄了使用腳本或在伺服器端執行它。 您可以看到一些 [純化樣品](https://github.com/cure53/DOMPurify?tab=readme-ov-file#some-purification-samples-please)並觀看[現場演示](https://cure53.de/purify)。 使用起來也非常簡單。 DOMPurify 於 2014 年 2 月啟動,同時版本已達 v3.1.0。 其中涉及到很多概念,我渴望探索它們。如果您有任何與此相關的令人興奮的事情,請告訴我。 我發現的另一個有用的替代方案是[validator.js](https://github.com/validatorjs/validator.js) 。 他們在 GitHub 上擁有超過 12,000 顆星,被超過 30 萬開發者使用,每週下載量超過 5,475,000 次,這使得他們非常可信。 {% cta https://github.com/cure53/DOMPurify %} 明星 DOMPurify ⭐️ {% endcta %} --- 18. [OpenDevin](https://github.com/OpenDevin/OpenDevin) - 更少的程式碼,更多的內容。 ----------------------------------------------------------------------- ![奧彭文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4on63bb02g4x4ny8gtcn.png) ![奧彭文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0yepod2rye2jk5r12dt.png) 這是一個開源專案,旨在複製 Devin,一名自主人工智慧軟體工程師,能夠執行複雜的工程任務並在軟體開發專案上與用戶積極協作。該計畫致力於透過開源社群的力量複製、增強和創新 Devin。 只是想讓你知道,這是在德文被介紹之前。 您可以閱讀帶有要求的[安裝說明](https://github.com/OpenDevin/OpenDevin?tab=readme-ov-file#installation)。 他們使用 LiteLLM,因此您可以使用任何基礎模型來執行 OpenDevin,包括 OpenAI、Claude 和 Gemini。 如果您想為 OpenDevin 做出貢獻,您可以查看 [演示](https://github.com/OpenDevin/OpenDevin/blob/main/README.md#opendevin-code-less-make-more)和[貢獻指南](https://github.com/OpenDevin/OpenDevin/blob/main/CONTRIBUTING.md)。 它在 GitHub 上擁有超過 10,700 個 Star,並且正在快速成長。 {% cta https://github.com/OpenDevin/OpenDevin %} 明星 OpenDevin ⭐️ {% endcta %} --- 19. [Amplification-](https://github.com/amplication/amplication)後端開發平台。 ----------------------------------------------------------------------- ![放大](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w7yi3kvwrniredj4lp5r.png) 我想我們都同意,如果我們要達到標準,設定後端並從頭開始是很困難的。 我知道 Appwrite 和 Supabase 在功能方面要好得多,但每種情況都是獨特的,這可能會點擊而不是那些。 ![放大](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d5wud5sef1lpwzi8zdq2.png) Amplication 旨在徹底改變可擴展且安全的 Node.js 應用程式的建立。 他們消除了重複的編碼任務,並提供可立即投入生產的基礎設施程式碼,這些程式碼根據您的規範精心定制,並遵循行業最佳實踐。 其用戶友好的介面促進了 API、資料模型、資料庫、身份驗證和授權的無縫整合。 Amplication 建立在靈活的、基於插件的架構之上,允許輕鬆定製程式碼並提供大量整合選項。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3lc27fgvk8yearir13z.png) ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4zgix42tplg9hwko3a7u.png) 您可以閱讀[文件](https://docs.amplication.com/)並查看可用的[社群插件](https://docs.amplication.com/plugins-list/)清單。 他們還提供了[逐步教程](https://docs.amplication.com/tutorials/#step-by-step-tutorials),以幫助您使用 Angular 或 React 建立應用程式。 Amplification 在 GitHub 上擁有超過 13k 顆星,發布了 170 多個版本,因此它們不斷發展。 {% cta https://github.com/amplication/amplication %} 星狀放大 ⭐️ {% endcta %} --- 20. [Embla 旋轉木馬](https://github.com/davidjerleke/embla-carousel)-。 ------------------------------------------------------------------ ![Embla 旋轉木馬](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aj2expoo15t6xhgcm3hi.png) 我們都在應用程式中使用輪播,有時會切換到網格佈局,因為輪播並不總是好看,但這會改變您對輪播的看法。 我之所以了解 Embla Carousel,是因為 Shadcn/ui 在他們的 UI 系統中使用了它。 Embla Carousel 是一個簡單的輪播庫,具有出色的流暢運動和出色的滑動精度。它與庫無關、無依賴性且 100% 開源。 如果您不確定,我建議您查看[基本的實例](https://www.embla-carousel.com/examples/predefined/)。 ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/paqu3ozlvhk5km5746pe.png) ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8qxfvmn83et836zon4ua.png) ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abukp6j29gsaade7eci8.png) ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/locv2kqksvpl0ha8a9te.png) 我最喜歡的是視差,它可以提供非常酷且平滑的過渡。 它們支援 CDN、react、Vue、Svelte 和 Solid。 開始使用以下 npm 指令 (react)。 ``` npm install embla-carousel-react --save ``` 您可以這樣使用它。 Embla Carousel 提供了方便的 useEmblaCarousel 鉤子,用於與 React 無縫整合。最小的設定需要一個溢出包裝器和一個滾動容器。 `useEmblaCarousel`掛鉤將 Embla Carousel 選項作為第一個參數。您還需要使用 useEffect 存取 API ``` import React, { useEffect } from 'react' import useEmblaCarousel from 'embla-carousel-react' export function EmblaCarousel() { const [emblaRef, emblaApi] = useEmblaCarousel({ loop: false }) useEffect(() => { if (emblaApi) { console.log(emblaApi.slideNodes()) // Access API } }, [emblaApi]) return ( <div className="embla" ref={emblaRef}> <div className="embla__container"> <div className="embla__slide">Slide 1</div> <div className="embla__slide">Slide 2</div> <div className="embla__slide">Slide 3</div> </div> </div> ) } ``` 他們還提供了一組插件,您可以加入它們以實現自動播放等額外功能。 ``` npm install embla-carousel-autoplay --save ``` ``` import React, { useEffect } from 'react' import useEmblaCarousel from 'embla-carousel-react' import Autoplay from 'embla-carousel-autoplay' export function EmblaCarousel() { const [emblaRef] = useEmblaCarousel({ loop: false }, [Autoplay()]) return ( <div className="embla" ref={emblaRef}> <div className="embla__container"> <div className="embla__slide">Slide 1</div> <div className="embla__slide">Slide 2</div> <div className="embla__slide">Slide 3</div> </div> </div> ) } ``` 尋找[插件的完整列表](https://www.embla-carousel.com/plugins/),包括自動滾動和滾輪手勢。 您可以閱讀有關如何實現不同部分(例如斷點或上一個/下一個按鈕)的[文件](https://www.embla-carousel.com/get-started/)和[指南](https://www.embla-carousel.com/guides/)。 最讓我驚訝的部分是,您可以使用他們的[生成器](https://www.embla-carousel.com/examples/generator/)使用您自己的一組選項來產生自訂輪播。 ![發電機](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5wlq7l44bwl681644xf3.png) ![發電機](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2r1y3kr926h87clbqosw.png) 它們在 GitHub 上擁有 4.9K 顆星,並被超過 26000 名開發人員使用。如果我必須使用一個,我肯定會使用這個。 {% cta repo %} 明星名稱 ⭐️ {% endcta %} --- [21.Documenso](https://github.com/documenso/documenso) - 開源 DocuSign 替代方案。 -------------------------------------------------------------------------- ![文獻](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cttvudzx02wqsu04qt8v.gif) 如果您從事自由職業並需要簽署協議,這是最佳選擇。我們不應該浪費時間,而應該專注於重要的事情。 以數位方式簽署文件應該既快速又簡單,並且應該成為全球簽署的每個文件的最佳實踐。 如今,這在技術上相當簡單,但它也為每個簽名引入了一個新方:簽名工具提供者。 此專案的技術堆疊包括 TypeScript、Next.js、Prisma、Tailwind CSS、shadcn/ui、NextAuth.js、react-email、tRPC、@documenso/pdf-sign、React-PDF、PDF-Lib、Stripe 和韋爾塞爾。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ziz58jqi2qtl6p6sx62w.png) ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f8zrln5zlywkb6k10n09.png) 免費套餐可讓您每月簽署 10 份文件,這已經足夠了。 您可以閱讀本文以了解如何[設定專案](https://github.com/documenso/documenso?tab=readme-ov-file#developer-setup)。 您可以閱讀[文件](https://github.com/documenso/documenso?tab=readme-ov-file#developer-quickstart)。 我知道這不是一個非常廣泛的用例,但您仍然可以從程式碼中學習,因此這始終是一個優點。 他們在 GitHub 上擁有超過 5800 顆星,並且發布了`v1.5`版本。 不是很流行但非常有用。 {% cta https://github.com/documenso/documenso %} 明星 documenso ⭐️ {% endcta %} --- 哇! 這花了我很長很長的時間來寫。我希望你喜歡它。 我知道人工智慧工具有時太多了,但我們應該使用它們來讓我們的工作更輕鬆。我的意思是,這就是我們所做的正確的事情,讓生活變得更輕鬆。 我嘗試涵蓋廣泛的工具。 不管怎樣,請讓我們知道您的想法以及您計劃在您的工作流程中使用這些工具嗎? 祝你有美好的一天!直到下一次。 我建立了很多技術內容,因此如果您能在 Twitter 上關注我來支持我,我將不勝感激。 |如果你喜歡這類東西, 請關注我以了解更多:) | [![用戶名 Anmol_Codes 的 Twitter 個人資料](https://img.shields.io/badge/Twitter-d5d5d5?style=for-the-badge&logo=x&logoColor=0A0209)](https://twitter.com/Anmol_Codes) [![用戶名 Anmol-Baranwal 的 GitHub 個人資料](https://img.shields.io/badge/github-181717?style=for-the-badge&logo=github&logoColor=white)](https://github.com/Anmol-Baranwal) [![用戶名 Anmol-Baranwal 的 LinkedIn 個人資料](https://img.shields.io/badge/LinkedIn-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/Anmol-Baranwal/) | |------------|----------| 關注 Taipy 以了解更多此類內容。 {% 嵌入 https://dev.to/taipy %} --- 原文出處:https://dev.to/taipy/21-tools-to-take-your-dev-skills-to-the-moon-53mf

使用 AI-copilot(Next.js、gpt4、LangChain 和 CopilotKit)建立電子表格應用程式

**長話短說** -------- 在本文中,您將學習如何建立人工智慧驅動的電子表格應用程式,該應用程式允許您使用簡單的英語命令執行各種會計功能並輕鬆與資料互動。 我們將介紹如何: - 使用 Next.js 建立 Web 應用程式, - 使用 React Spreadsheet 建立電子表格應用程式,以及 - 使用 CopilotKit 將 AI 整合到軟體應用程式中。 - 讓電子表格更容易使用、更有趣 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ruxylrd07dga5ngw98np.gif) --- CopilotKit:建構應用內人工智慧副駕駛的框架 ========================== CopilotKit是一個[開源的AI副駕駛平台](https://github.com/CopilotKit/CopilotKit)。我們可以輕鬆地將強大的人工智慧整合到您的 React 應用程式中。 建造: - ChatBot:上下文感知的應用內聊天機器人,可以在應用程式內執行操作 💬 - CopilotTextArea:人工智慧驅動的文字字段,具有上下文感知自動完成和插入功能📝 - 聯合代理:應用程式內人工智慧代理,可以與您的應用程式和使用者互動🤖 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x3us3vc140aun0dvrdof.gif) {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} (請原諒 AI 的拼字錯誤並給 CopilotKit 加上星號:) 現在回到文章! --- 先決條件 ---- 要完全理解本教程,您需要對 React 或 Next.js 有基本的了解。 以下是建立人工智慧驅動的電子表格應用程式所需的工具: - [React Spreadsheet](https://github.com/iddan/react-spreadsheet) - 一個簡單的包,使我們能夠在 React 應用程式中加入電子表格。 - [OpenAI API](https://platform.openai.com/api-keys) - 提供 API 金鑰,使我們能夠使用 ChatGPT 模型執行各種任務。 - [Tavily AI](https://tavily.com/) - 一個搜尋引擎,使人工智慧代理能夠在應用程式中進行研究並存取即時知識。 - [CopilotKit](https://github.com/CopilotKit) - 一個開源副駕駛框架,用於建立自訂 AI 聊天機器人、應用程式內 AI 代理程式和文字區域。 專案設定和套件安裝 --------- 首先,透過在終端機中執行以下程式碼片段來建立 Next.js 應用程式: ``` npx create-next-app spreadsheet-app ``` 選擇您首選的配置設定。在本教學中,我們將使用 TypeScript 和 Next.js App Router。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2zg8z22tdgmlv4wmfil.png) 接下來,安裝[OpenAI 函式庫](https://platform.openai.com/docs/introduction)、 [Heroicons](https://www.npmjs.com/package/@heroicons/react)和[React Spreadsheet](https://github.com/iddan/react-spreadsheet)套件及其相依性: ``` npm install openai react-spreadsheet scheduler @heroicons/react ``` 最後,安裝 CopilotKit 軟體套件。這些套件使我們能夠從 React 狀態檢索資料並將 AI copilot 新增至應用程式。 ``` npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend ``` 恭喜!您現在已準備好建立應用程式。 --- 建立電子表格應用程式 ---------- 在本節中,我將引導您使用 React Spreadsheet 建立電子表格應用程式。 該應用程式分為兩個元件: `Sidebar`和`SingleSpreadsheet` 。 要設定這些元件,請導航至 Next.js 應用程式資料夾並建立一個包含以下檔案的`components`資料夾: ``` cd app mkdir components && cd components touch Sidebar.tsx SingleSpreadsheet.tsx ``` ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bd9crph3qdenb2eikfoh.png) 將新建立的元件匯入到**`app/page.tsx`**檔案中。 ``` "use client"; import React, { useState } from "react"; //👇🏻 import the components import { SpreadsheetData } from "./types"; import Sidebar from "./components/Sidebar"; import SingleSpreadsheet from "./components/SingleSpreadsheet"; const Main = () => { return ( <div className='flex'> <p>Hello world</p> </div> ); }; export default Main; ``` 接下來,建立將包含電子表格資料的 React 狀態,並將它們作為 props 傳遞到元件中。 ``` const Main = () => { //👇🏻 holds the title and data within a spreadsheet const [spreadsheets, setSpreadsheets] = React.useState<SpreadsheetData[]>([ { title: "Spreadsheet 1", data: [ [{ value: "" }, { value: "" }, { value: "" }], [{ value: "" }, { value: "" }, { value: "" }], [{ value: "" }, { value: "" }, { value: "" }], ], }, ]); //👇🏻 represents the index of a spreadsheet const [selectedSpreadsheetIndex, setSelectedSpreadsheetIndex] = useState(0); return ( <div className='flex'> <Sidebar spreadsheets={spreadsheets} selectedSpreadsheetIndex={selectedSpreadsheetIndex} setSelectedSpreadsheetIndex={setSelectedSpreadsheetIndex} /> <SingleSpreadsheet spreadsheet={spreadsheets[selectedSpreadsheetIndex]} setSpreadsheet={(spreadsheet) => { setSpreadsheets((prev) => { console.log("setSpreadsheet", spreadsheet); const newSpreadsheets = [...prev]; newSpreadsheets[selectedSpreadsheetIndex] = spreadsheet; return newSpreadsheets; }); }} /> </div> ); }; ``` 此程式碼片段建立了 React 狀態,用於保存電子表格資料及其索引,並將它們作為 props 傳遞到元件中。 `Sidebar`元件接受所有可用的電子表格, `SingleSpreadsheet`元件接收所有電子表格,包括更新電子表格資料的`setSpreadsheet`函數。 將下面的程式碼片段複製到`Sidebar.tsx`檔案中。它顯示應用程式中的所有電子表格,並允許使用者在它們之間進行切換。 ``` import React from "react"; import { SpreadsheetData } from "../types"; interface SidebarProps { spreadsheets: SpreadsheetData[]; selectedSpreadsheetIndex: number; setSelectedSpreadsheetIndex: (index: number) => void; } const Sidebar = ({ spreadsheets, selectedSpreadsheetIndex, setSelectedSpreadsheetIndex, }: SidebarProps) => { return ( <div className='w-64 h-screen bg-gray-800 text-white overflow-auto p-5'> <ul> {spreadsheets.map((spreadsheet, index) => ( <li key={index} className={`mb-4 cursor-pointer ${ index === selectedSpreadsheetIndex ? "ring-2 ring-blue-500 ring-inset p-3 rounded-lg" : "p-3" }`} onClick={() => setSelectedSpreadsheetIndex(index)} > {spreadsheet.title} </li> ))} </ul> </div> ); }; export default Sidebar; ``` ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c36qccuwa0knqokag5mk.gif) 更新`SingleSpreadsheet.tsx`文件,如下所示: ``` import React from "react"; import Spreadsheet from "react-spreadsheet"; import { SpreadsheetData, SpreadsheetRow } from "../types"; interface MainAreaProps { spreadsheet: SpreadsheetData; setSpreadsheet: (spreadsheet: SpreadsheetData) => void; } //👇🏻 adds a new row to the spreadsheet const addRow = () => { const numberOfColumns = spreadsheet.rows[0].length; const newRow: SpreadsheetRow = []; for (let i = 0; i < numberOfColumns; i++) { newRow.push({ value: "" }); } setSpreadsheet({ ...spreadsheet, rows: [...spreadsheet.rows, newRow], }); }; //👇🏻 adds a new column to the spreadsheet const addColumn = () => { const spreadsheetData = [...spreadsheet.data]; for (let i = 0; i < spreadsheet.data.length; i++) { spreadsheet.data[i].push({ value: "" }); } setSpreadsheet({ ...spreadsheet, data: spreadsheetData, }); }; const SingleSpreadsheet = ({ spreadsheet, setSpreadsheet }: MainAreaProps) => { return ( <div className='flex-1 overflow-auto p-5'> {/** -- Spreadsheet title ---*/} <div className='flex items-start'> {/** -- Spreadsheet rows and columns---*/} {/** -- Add column button ---*/} </div> {/** -- Add row button ---*/} </div> ); }; export default SingleSpreadsheet; ``` - 從上面的程式碼片段來看, ``` - The `SingleSpreadsheet.tsx` file includes the addRow and addColumn functions. ``` ``` - The `addRow` function calculates the current number of rows, adds a new row, and updates the spreadsheet accordingly. ``` ``` - Similarly, the `addColumn` function adds a new column to the spreadsheet. ``` ``` - The `SingleSpreadsheet` component renders placeholders for the user interface elements. ``` 更新`SingleSpreadsheet`元件以呈現電子表格標題、其資料以及新增行和列按鈕。 ``` return ( <div className='flex-1 overflow-auto p-5'> {/** -- Spreadsheet title ---*/} <input type='text' value={spreadsheet.title} className='w-full p-2 mb-5 text-center text-2xl font-bold outline-none bg-transparent' onChange={(e) => setSpreadsheet({ ...spreadsheet, title: e.target.value }) } /> {/** -- Spreadsheet rows and columns---*/} <div className='flex items-start'> <Spreadsheet data={spreadsheet.data} onChange={(data) => { console.log("data", data); setSpreadsheet({ ...spreadsheet, data: data as any }); }} /> {/** -- Add column button ---*/} <button className='bg-blue-500 text-white rounded-lg ml-6 w-8 h-8 mt-0.5' onClick={addColumn} > + </button> </div> {/** -- Add row button ---*/} <button className='bg-blue-500 text-white rounded-lg w-8 h-8 mt-5 ' onClick={addRow} > + </button> </div> ); ``` 為了確保一切按預期工作,請在`app`資料夾中建立一個`types.ts`文件,其中包含應用程式中聲明的所有靜態類型。 ``` export interface Cell { value: string; } export type SpreadsheetRow = Cell[]; export interface SpreadsheetData { title: string; rows: SpreadsheetRow[]; } ``` 恭喜! 🎉 您的電子表格應用程式應該可以完美執行。在接下來的部分中,您將了解如何新增 AI 副駕駛,以使用 CopilotKit 自動執行各種任務。 --- 使用 CopilotKit 改進應用程式功能 ---------------------- 在這裡,您將學習如何將 AI 副駕駛加入到電子表格應用程式,以使用 CopilotKit 自動執行複雜的操作。 CopilotKit 提供前端和[後端](https://docs.copilotkit.ai/getting-started/quickstart-backend)套件。它們使您能夠插入 React 狀態並使用 AI 代理在後端處理應用程式資料。 首先,我們將 CopilotKit React 元件新增到應用程式前端。 ### 將 CopilotKit 加入前端 在`app/page.tsx`中,將以下程式碼片段加入`Main`元件的頂部。 ``` import "@copilotkit/react-ui/styles.css"; import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import { INSTRUCTIONS } from "./instructions"; const HomePage = () => { return ( <CopilotKit url='/api/copilotkit'> <CopilotSidebar instructions={INSTRUCTIONS} labels={{ initial: "Welcome to the spreadsheet app! How can I help you?", }} defaultOpen={true} clickOutsideToClose={false} > <Main /> </CopilotSidebar> </CopilotKit> ); }; const Main = () => { //--- Main component // }; export default HomePage; ``` - 從上面的程式碼片段來看, ``` - I imported the CopilotKit, its sidebar component, and CSS file to use its frontend components within the application. ``` ``` - The [CopilotKit component](https://docs.copilotkit.ai/reference/CopilotKit) accepts a `url` prop that represents the API server route where CopilotKit will be configured. ``` ``` - The Copilot component also renders the [CopilotSidebar component](https://docs.copilotkit.ai/reference/CopilotSidebar) , allowing users to provide custom instructions to the AI copilot within the application. ``` ``` - Lastly, you can export the `HomePage` component containing the `CopilotSidebar` and the `Main` components. ``` 從上面的程式碼片段中,您會注意到`CopilotSidebar`元件有一個`instructions`屬性。此屬性使您能夠為 CopilotKit 提供額外的上下文或指導。 因此,在`app`資料夾中建立`instructions.ts`檔案並將這些[命令](https://github.com/CopilotKit/spreadsheet-demo/blob/main/src/app/instructions.ts)複製到該檔案中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/whs8k2ly9as7j4wn6h5o.png) 接下來,您需要將 CopilotKit 插入應用程式的狀態以存取應用程式的資料。為了實現這一點,CopilotKit 提供了兩個鉤子: [useCopilotAction](https://docs.copilotkit.ai/reference/useCopilotAction)和[useMakeCopilotReadable](https://docs.copilotkit.ai/reference/useMakeCopilotReadable) 。 [useCopilotAction](https://docs.copilotkit.ai/reference/useCopilotAction)掛鉤可讓您定義 CopilotKit 執行的動作。它接受包含以下參數的物件: - `name` - 操作的名稱。 - `description` - 操作的描述。 - `parameters` - 包含所需參數清單的陣列。 - `render` - 預設的自訂函數或字串。 - `handler` - 由操作觸發的可執行函數。 ``` useCopilotAction({ name: "sayHello", description: "Say hello to someone.", parameters: [ { name: "name", type: "string", description: "name of the person to say greet", }, ], render: "Process greeting message...", handler: async ({ name }) => { alert(`Hello, ${name}!`); }, }); ``` [useMakeCopilotReadable](https://docs.copilotkit.ai/reference/useMakeCopilotReadable)掛鉤向 CopilotKit 提供應用程式狀態。 ``` import { useMakeCopilotReadable } from "@copilotkit/react-core"; const appState = ...; useMakeCopilotReadable(JSON.stringify(appState)); ``` 現在,讓我們回到電子表格應用程式。在`SingleSpreadsheet`元件中,將應用程式狀態傳遞到 CopilotKit 中,如下所示。 ``` import { useCopilotAction, useMakeCopilotReadable, } from "@copilotkit/react-core"; const SingleSpreadsheet = ({ spreadsheet, setSpreadsheet }: MainAreaProps) => { //👇🏻 hook for providing the application state useMakeCopilotReadable( "This is the current spreadsheet: " + JSON.stringify(spreadsheet) ); // --- other lines of code }; ``` 接下來,您需要在`SingleSpreadsheet`元件中新增兩個操作,該元件在使用者更新電子表格資料並使用 CopilotKit 新增資料行時執行。 在繼續之前,請在`app`資料夾中建立一個包含`canonicalSpreadsheetData.ts`檔案的`utils`資料夾。 ``` cd app mkdir utils && cd utils touch canonicalSpreadsheetData.ts ``` 將下面的程式碼片段複製到檔案中。它接受對電子表格所做的更新,並將其轉換為電子表格中資料行所需的格式。 ``` import { SpreadsheetRow } from "../types" export interface RowLike { cells: CellLike[] | undefined; } export interface CellLike { value: string; } export function canonicalSpreadsheetData( rows: RowLike[] | undefined ): SpreadsheetRow[] { const canonicalRows: SpreadsheetRow[] = []; for (const row of rows || []) { const canonicalRow: SpreadsheetRow = []; for (const cell of row.cells || []) { canonicalRow.push({value: cell.value}); } canonicalRows.push(canonicalRow); } return canonicalRows; } ``` 現在,讓我們使用`SingleSpreadsheet`元件中的`useCopilotAction`掛鉤建立操作。複製下面的第一個操作: ``` import { canonicalSpreadsheetData } from "../utils/canonicalSpreadsheetData"; import { PreviewSpreadsheetChanges } from "./PreviewSpreadsheetChanges"; import { SpreadsheetData, SpreadsheetRow } from "../types"; import { useCopilotAction } from "@copilotkit/react-core"; useCopilotAction({ name: "suggestSpreadsheetOverride", description: "Suggest an override of the current spreadsheet", parameters: [ { name: "rows", type: "object[]", description: "The rows of the spreadsheet", attributes: [ { name: "cells", type: "object[]", description: "The cells of the row", attributes: [ { name: "value", type: "string", description: "The value of the cell", }, ], }, ], }, { name: "title", type: "string", description: "The title of the spreadsheet", required: false, }, ], render: (props) => { const { rows } = props.args const newRows = canonicalSpreadsheetData(rows); return ( <PreviewSpreadsheetChanges preCommitTitle="Replace contents" postCommitTitle="Changes committed" newRows={newRows} commit={(rows) => { const updatedSpreadsheet: SpreadsheetData = { title: spreadsheet.title, rows: rows, }; setSpreadsheet(updatedSpreadsheet); }} /> ) }, handler: ({ rows, title }) => { // Do nothing. // The preview component will optionally handle committing the changes. }, }); ``` 上面的程式碼片段執行使用者的任務並使用 CopilotKit 產生 UI 功能顯示結果預覽。 `suggestSpreadsheetOverride`操作傳回一個自訂元件 ( `PreviewSpreadsheetChanges` ),該元件接受以下內容為 props: - 要新增到電子表格的新資料行, - 一些文字 - `preCommitTitle`和`postCommitTitle` ,以及 - 更新電子表格的`commit`函數。 您很快就會學會如何使用它們。 在元件資料夾中建立`PreviewSpreadsheetChanges`元件,並將下列程式碼片段複製到檔案中: ``` import { CheckCircleIcon } from '@heroicons/react/20/solid' import { SpreadsheetRow } from '../types'; import { useState } from 'react'; import Spreadsheet from 'react-spreadsheet'; export interface PreviewSpreadsheetChanges { preCommitTitle: string; postCommitTitle: string; newRows: SpreadsheetRow[]; commit: (rows: SpreadsheetRow[]) => void; } export function PreviewSpreadsheetChanges(props: PreviewSpreadsheetChanges) { const [changesCommitted, setChangesCommitted] = useState(false); const commitChangesButton = () => { return ( <button className="inline-flex items-center gap-x-2 rounded-md bg-indigo-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600" onClick={() => { props.commit(props.newRows); setChangesCommitted(true); }} > {props.preCommitTitle} </button> ); } const changesCommittedButtonPlaceholder = () => { return ( <button className=" inline-flex items-center gap-x-2 rounded-md bg-gray-100 px-3.5 py-2.5 text-sm font-semibold text-green-600 shadow-sm cursor-not-allowed" disabled > {props.postCommitTitle} <CheckCircleIcon className="-mr-0.5 h-5 w-5" aria-hidden="true" /> </button> ); } return ( <div className="flex flex-col"> <Spreadsheet data={props.newRows} /> <div className="mt-5"> {changesCommitted ? changesCommittedButtonPlaceholder() : commitChangesButton() } </div> </div> ); } ``` `PreviewSpreadsheetChanges`元件傳回一個電子表格,其中包含從請求產生的資料和一個按鈕(帶有`preCommitTitle`文字),該按鈕允許您將這些變更提交到主電子表格表(透過觸發`commit`函數)。這可確保您在將結果新增至電子表格之前對結果感到滿意。 將下面的第二個操作加入到`SingleSpreadsheet`元件。 ``` useCopilotAction({ name: "appendToSpreadsheet", description: "Append rows to the current spreadsheet", parameters: [ { name: "rows", type: "object[]", description: "The new rows of the spreadsheet", attributes: [ { name: "cells", type: "object[]", description: "The cells of the row", attributes: [ { name: "value", type: "string", description: "The value of the cell", }, ], }, ], }, ], render: (props) => { const status = props.status; const { rows } = props.args const newRows = canonicalSpreadsheetData(rows); return ( <div> <p>Status: {status}</p> <Spreadsheet data={newRows} /> </div> ) }, handler: ({ rows }) => { const canonicalRows = canonicalSpreadsheetData(rows); const updatedSpreadsheet: SpreadsheetData = { title: spreadsheet.title, rows: [...spreadsheet.rows, ...canonicalRows], }; setSpreadsheet(updatedSpreadsheet); }, }); ``` `appendToSpreadsheet`操作透過在電子表格中新增資料行來更新電子表格。 以下是操作的簡短示範: \[https://www.youtube.com/watch?v=kGQ9xl5mSoQ\] 最後,在`Main`元件中新增一個操作,以便在使用者提供指令時建立一個新的電子表格。 ``` useCopilotAction({ name: "createSpreadsheet", description: "Create a new spreadsheet", parameters: [ { name: "rows", type: "object[]", description: "The rows of the spreadsheet", attributes: [ { name: "cells", type: "object[]", description: "The cells of the row", attributes: [ { name: "value", type: "string", description: "The value of the cell", }, ], }, ], }, { name: "title", type: "string", description: "The title of the spreadsheet", }, ], render: (props) => { const { rows, title } = props.args; const newRows = canonicalSpreadsheetData(rows); return ( <PreviewSpreadsheetChanges preCommitTitle="Create spreadsheet" postCommitTitle="Spreadsheet created" newRows={newRows} commit={ (rows) => { const newSpreadsheet: SpreadsheetData = { title: title || "Untitled Spreadsheet", rows: rows, }; setSpreadsheets((prev) => [...prev, newSpreadsheet]); setSelectedSpreadsheetIndex(spreadsheets.length); }} /> ); }, handler: ({ rows, title }) => { // Do nothing. // The preview component will optionally handle committing the changes. }, }); ``` 恭喜!您已成功為此應用程式建立所需的操作。現在,讓我們將應用程式連接到 Copilotkit 後端。 ### 將 Tavily AI 和 OpenAI 加入到 CopilotKit 在本教程的開頭,我向您介紹了[Tavily AI](https://tavily.com/) (一個為 AI 代理提供知識的搜尋引擎)和 OpenAI(一個使我們能夠存取[GPT-4 AI 模型的](https://openai.com/gpt-4)庫)。 在本部分中,您將了解如何取得 Tavily 和 OpenAI API 金鑰並將它們整合到 CopilotKit 中以建立高級智慧應用程式。 造訪[Tavily AI 網站](https://app.tavily.com/sign-in),建立一個帳戶,然後將您的 API 金鑰複製到您專案的`.env.local`檔案中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w8shpxr5hh9r9kggk1jv.png) 接下來,導覽至[OpenAI 開發者平台](https://platform.openai.com/api-keys),建立 API 金鑰,並將其複製到`.env.local`檔案中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f4ugtobr70wg6z6ru3cj.png) 以下是`.env.local`檔案的預覽,其中包括 API 金鑰並指定要使用的 OpenAI 模型。請注意,存取 GPT-4 模型需要[訂閱 ChatGPT Plus](https://openai.com/chatgpt/pricing) 。 ``` TAVILY_API_KEY=<your_API_key> OPENAI_MODEL=gpt-4-1106-preview OPENAI_API_KEY=<your_API_key> ``` 回到我們的應用程式,您需要為 Copilot 建立 API 路由。因此,建立一個包含`route.ts`的`api/copilotkit`資料夾並新增一個`tavily.ts`檔案。 ``` cd app mkdir api && cd api mkdir copilotkit && cd copilotkit touch route.ts tavily.ts ``` 在`tavily.ts`檔案中建立一個函數,該函數接受使用者的查詢,使用 Tavily Search API 對查詢進行研究,並使用[OpenAI GPT-4 模型](https://openai.com/gpt-4)總結結果。 ``` import OpenAI from "openai"; export async function research(query: string) { //👇🏻 sends the request to the Tavily Search API const response = await fetch("https://api.tavily.com/search", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ api_key: process.env.TAVILY_API_KEY, query, search_depth: "basic", include_answer: true, include_images: false, include_raw_content: false, max_results: 20, }), }); //👇🏻 the response const responseJson = await response.json(); const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY! }); //👇🏻 passes the response into the OpenAI GPT-4 model const completion = await openai.chat.completions.create({ messages: [ { role: "system", content: `Summarize the following JSON to answer the research query \`"${query}"\`: ${JSON.stringify( responseJson )} in plain English.`, }, ], model: process.env.OPENAI_MODEL, }); //👇🏻 returns the result return completion.choices[0].message.content; } ``` 最後,您可以透過將使用者的查詢傳遞到函數中並向 CopilotKit 提供其回應來執行`route.ts`檔案中的`research`函數。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; import { Action } from "@copilotkit/shared"; import { research } from "./tavily"; //👇🏻 carries out a research on the user's query const researchAction: Action<any> = { name: "research", description: "Call this function to conduct research on a certain query.", parameters: [ { name: "query", type: "string", description: "The query for doing research. 5 characters or longer. Might be multiple words", }, ], handler: async ({ query }) => { console.log("Research query: ", query); const result = await research(query); console.log("Research result: ", result); return result; }, }; export async function POST(req: Request): Promise<Response> { const actions: Action<any>[] = []; if (process.env.TAVILY_API_KEY!) { actions.push(researchAction); } const copilotKit = new CopilotBackend({ actions: actions, }); const openaiModel = process.env.OPENAI_MODEL; return copilotKit.response(req, new OpenAIAdapter({ model: openaiModel })); } ``` 恭喜!您已完成本教學的專案。 結論 -- [CopilotKit](https://copilotkit.ai/)是一款令人難以置信的工具,可讓您在幾分鐘內將 AI Copilot 加入到您的產品中。無論您是對人工智慧聊天機器人和助理感興趣,還是對複雜任務的自動化感興趣,CopilotKit 都能讓您輕鬆實現。 如果您需要建立 AI 產品或將 AI 工具整合到您的軟體應用程式中,您應該考慮 CopilotKit。 您可以在 GitHub 上找到本教學的源程式碼: https://github.com/CopilotKit/spreadsheet-demo 感謝您的閱讀! --- 原文出處:https://dev.to/copilotkit/build-an-ai-powered-spreadsheet-app-nextjs-langchain-copilotkit-109d

從頭開始實作 JavaScript 概念

在本文中,我們透過從頭開始建立幾個關鍵元件來探索 JavaScript 的基本建構塊。當我們深入研究這些概念時,我們將應用一系列從基礎到複雜的技術,使這種探索對於 JavaScript 世界的新手和專業人士都很有價值。 大綱 ---- - [`memoize()`](#memoize) - [`Array.map()`](#arraymap) - [`Array.filter()`](#arrayfilter) - [`Array.reduce()`](#arrayreduce) - [`bind()`](#bind) - [`call()` 、 `apply()`](#callapply) - [`setInterval()`](#setinterval) - [`cloneDeep()`](#clonedeep) - [`debounce()`](#debounce) - [`throttle()`](#throttle) - [`Promise`](#promise) - \[ `EventEmitter` ) <a name="memoize"></a> `memoize()` ----------- ### 任務說明 重新建立`memoize`函數(來自“lodash”),該函數透過快取函數呼叫的結果來優化效能。透過傳回快取的結果而不是重新計算,可以確保使用相同參數的重複函數呼叫更快。 ### 執行 ``` function customSerializer(entity, cache = new WeakSet()) { if (typeof entity !== 'object' || entity === null) { return `${typeof entity}:${entity}`; } if (cache.has(entity)) { return 'CircularReference'; } cache.add(entity); let objKeys = Object.keys(entity).sort(); let keyRepresentations = objKeys.map(key => `${customSerializer(key, cache)}:${ customSerializer(entity[key], cache) }` ); if (Array.isArray(entity)) { return `Array:[${keyRepresentations.join(',')}]`; } return `Object:{${keyRepresentations.join(',')}}`; } function myMemoize(fn) { const cache = new Map(); return function memoized(...args) { const keyRep = args.map(arg => customSerializer(arg) ).join('-'); const key = `${typeof this}:${this}-${keyRep}`; if (cache.has(key)) { return cache.get(key); } else { const result = fn.apply(this, args); cache.set(key, result); return result; } }; } ``` ### 實施的關鍵面 1. **快取機制:**它使用`Map`物件`cache`來儲存函數呼叫的結果。選擇`Map`物件是因為其高效率的鍵值配對和檢索功能。 2. **Custom Serializer** : `customSerializer`函數將函數參數轉換為用作快取鍵的字串表示形式。此序列化考慮了基本類型、物件(包括巢狀物件)、陣列和循環參考。對於物件和陣列,它們的鍵經過排序以確保一致的字串表示形式,無論屬性聲明順序如何。 3. **序列化`this`** : `this`的值指的是函數所屬的物件。在 JavaScript 中,方法可以根據呼叫它們的物件(即呼叫它們的上下文)而有不同的行為。這是因為`this`提供了對上下文物件的屬性和方法的存取,並且其值可能會根據函數的呼叫方式而變化。 4. **循環引用**:當物件直接或透過其屬性間接引用自身時,就會發生循環引用。這可能發生在更複雜的資料結構中,例如,物件`A`包含對物件`B`的引用,而物件`B`則直接或間接引用物件`A` 。處理循環引用以避免無限循環至關重要。 5. **使用`WeakSet`進行自動垃圾收集**: `WeakSet`保留對其物件的「弱」引用,這表示如果沒有其他引用, `WeakSet`中物件的存在不會阻止該物件被垃圾收集。此行為在需要臨時追蹤物件存在而又不會不必要地延長其生命週期的情況下特別有用。由於`customSerializer`函數可能只需要在序列化過程中標記物件的存取,而不儲存額外的資料,因此使用`WeakSet`可以確保物件不會僅僅因為它們在集合中的存在而保持活動狀態,從而防止潛在的內存洩漏。 <a name="arraymap"></a> `Array.map()` ------------- ### 任務說明 重新建立`Array.map()` ,它將轉換函數作為參數。此轉換函數將在陣列的每個元素上執行,並採用三個參數:當前元素、目前元素的索引和陣列本身。 ### 實施的關鍵面 1. **記憶體預先分配**: `new Array(this.length)`用於建立預先確定大小的陣列,以優化記憶體分配並透過避免加入元素時動態調整大小來提高效能。 ### 執行 ``` Array.prototype.myMap = function(fn) { const result = new Array(this.length); for (let i = 0; i < this.length; i++) { result[i] = fn(this[i], i, this); } return result; } ``` <a name="arrayfilter"></a> `Array.filter()` ---------------- ### 任務說明 重新建立`Array.filter()` ,它將謂詞函數作為輸入,迭代呼叫它的陣列的元素,將謂詞應用於每個元素。它傳回一個新陣列,僅包含謂詞函數傳回`true`元素。 ### 實施的關鍵面 1. **動態記憶體分配**:它動態地將符合條件的元素加入到`filteredArray`中,從而在很少有元素通過謂詞函數的情況下使該方法更有效地使用記憶體。 ### 執行 ``` Array.prototype.myFilter = function(pred) { const filteredArray = []; for (let i = 0; i < this.length; i++) { if (pred(this[i], i, this)) { filteredArray.push(this[i]); } } return filteredArray; } ``` <a name="arrayreduce"></a> `Array.reduce()` ---------------- ### 任務說明 重新建立`Array.reduce()` ,它對陣列的每個元素執行`reducer`函數,從而產生單一輸出值。 `reducer`函數有四個參數:累加器、currentValue、currentIndex 和整個陣列。 ### 實施的關鍵面 1. **`initialValue` value** : `accumulator`和`startIndex`會根據是否將`initialValue`作為參數傳遞來初始化。如果提供了`initialValue` (意味著`arguments.length`至少為`2` ),則`accumulator`設定為此`initialValue` ,並且迭代從第0個元素開始。否則,如果未提供`initialValue` ,則將陣列本身的第 0 個元素用作`initialValue` 。 ### 執行 ``` Array.prototype.myReduce = function(callback, initialValue) { let accumulator = arguments.length >= 2 ? initialValue : this[0]; let startIndex = arguments.length >= 2 ? 0 : 1; for (let i = startIndex; i < this.length; i++) { accumulator = callback(accumulator, this[i], i, this); } return accumulator; } ``` <a name="bind"></a> `bind()` -------- ### 任務說明 重新建立`bind()`函數,該函數允許將物件以及預先指定的初始參數(如果有)作為呼叫原始函數的上下文傳遞。它還應該支援`new`運算符的使用,從而能夠建立新實例,同時維護正確的原型鏈。 ### 執行 ``` Function.prototype.mybind = function(context, ...bindArgs) { const self = this; const boundFunction = function(...callArgs) { const isNewOperatorUsed = new.target !== undefined; const thisContext = isNewOperatorUsed ? this : context; return self.apply(thisContext, bindArgs.concat(callArgs)); }; if (self.prototype) { boundFunction.prototype = Object.create(self.prototype); } return boundFunction; }; ``` ### 實施的關鍵面 1. **處理`new` Operator** :語句`const isNewOperatorUsed = new.target !== undefined;`檢查是否透過`new`運算子將`boundFunction`作為建構函數呼叫。如果使用`new`運算符,則`thisContext`將設定為新建立的物件 ( `this` ) 而不是提供的`context` ,確認實例化應使用新的上下文而不是綁定期間提供的上下文。 2. **原型保留**:為了維護原始函數的原型鏈, `mybind`有條件地將`boundFunction`的原型設定為繼承自`self.prototype`的新物件。此步驟確保從`boundFunction` (用作建構函數時)建立的實例正確地繼承原始函數原型的屬性。此機制保留了預期的繼承層次結構並維護instanceof 檢查。 ### 將`bind()`與`new`一起使用的範例 讓我們考慮一個簡單的建構函數,它建立代表汽車的物件: ``` function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } ``` 想像一下,我們常常創造「豐田」品牌的`Car`物件。為了讓這個過程更有效率,我們可以使用`bind`為Toyotas建立一個專門的建構函數,預先填入`make`參數: ``` // Creating a specialized Toyota constructor with 'Toyota' // as the pre-set 'make' const ToyotaConstructor = Car.bind(null, 'Toyota'); // Now, we can create Toyota car instances // without specifying 'make' const myCar = new ToyotaConstructor('Camry', 2020); // Output: Car { make: 'Toyota', model: 'Camry', year: 2020 } console.log(myCar); ``` <a name="callapply"></a> `call()` 、 `apply()` -------------------- ### 任務說明 重新建立`call()`和`apply()`函數,它們允許使用給定的 this 值和單獨提供的參數來呼叫函數。 ### 執行 ``` Function.prototype.myCall = function(context, ...args) { const fnSymbol = Symbol('fnSymbol'); context[fnSymbol] = this; const result = context[fnSymbol](...args); delete context[fnSymbol]; return result; }; Function.prototype.myApply = function(context, args) { const fnSymbol = Symbol('fnSymbol'); context[fnSymbol] = this; const result = context[fnSymbol](...args); delete context[fnSymbol]; return result; }; ``` ### 實施的關鍵面 1. **屬性命名的符號用法**:為了防止覆蓋上下文物件上潛在的現有屬性或由於名稱衝突而導致意外行為,使用唯一的`Symbol`作為屬性名稱。這確保了我們的臨時屬性不會幹擾上下文物件的原始屬性。 2. **執行後清理**:函數呼叫執行後,新增到上下文物件中的臨時屬性將被刪除。此清理步驟對於避免在上下文物件上留下修改後的狀態至關重要。 <a name="setinterval"></a> `setInterval()` --------------- ### 任務說明 使用`setTimeout`重新建立`setInterval` 。此函數應以指定的時間間隔重複呼叫提供的回呼函數。它會傳回一個函數,當呼叫該函數時,該函數會停止間隔。 ### 執行 ``` function mySetInterval(callback, interval) { let timerId; const repeater = () => { callback(); timerId = setTimeout(repeater, interval); }; repeater(); return () => { clearTimeout(timerId); }; } ``` ### 實施的關鍵面 1. **取消功能**: `mySetInterval`傳回的函數提供了一種簡單直接的方法來取消正在進行的間隔,而無需在函數範圍之外公開或管理計時器 ID。 <a name="clonedeep"></a> `cloneDeep()` ------------- ### 任務說明 重新建立執行給定輸入的深度複製的`cloneDeep`函數(來自“lodash”)。該函數應該能夠複製複雜的資料結構,包括物件、陣列、映射、集合、日期和正規表示式,並保持每個元素的結構和類型完整性。 ### 執行 ``` function myCloneDeep(entity, map = new WeakMap()) { if (entity === null || typeof entity !== 'object') { return entity; } if (map.has(entity)) { return map.get(entity); } let cloned; switch (true) { case Array.isArray(entity): cloned = []; map.set(entity, cloned); cloned = entity.map(item => myCloneDeep(item, map)); break; case entity instanceof Date: cloned = new Date(entity.getTime()); break; case entity instanceof Map: cloned = new Map(Array.from(entity.entries(), ([key, val]) => [myCloneDeep(key, map), myCloneDeep(val, map)])); break; case entity instanceof Set: cloned = new Set(Array.from(entity.values(), val => myCloneDeep(val, map))); break; case entity instanceof RegExp: cloned = new RegExp(entity.source, entity.flags); break; default: cloned = Object.create( Object.getPrototypeOf(entity)); map.set(entity, cloned); for (let key in entity) { if (entity.hasOwnProperty(key)) { cloned[key] = myCloneDeep(entity[key], map); } } } return cloned; } ``` ### 實施的關鍵面 1. **循環引用處理**:利用`WeakMap`來追蹤已存取的物件。如果遇到已經克隆的物件,則返回先前克隆的物件,有效處理循環參考並防止堆疊溢位錯誤。 2. **特殊物件的處理**:區分幾種物件類型( `Array` 、 `Date` 、 `Map` 、 `Sets` 、 `RegExp` ),以確保每種類型都被適當地克隆,並保留其特定特徵。 ``` - **`Array`**: Recursively clones each element, ensuring deep cloning. ``` ``` - **`Date`**: Copies the date using its numeric value (timestamp). ``` ``` - **Maps and Sets**: Constructs a new instance, recursively cloning each entry (for `Map`) or value (for `Set`). ``` ``` - **`RegExp`**: Clones by creating a new instance with the source and flags of the original. ``` 3. **物件屬性的複製**:當輸入是普通物件時,它會建立一個與原始物件具有相同原型的物件,然後遞歸地複製每個自己的屬性,在保持原型鏈的同時確保深度克隆。 4. **效率和性能**:利用`WeakMap`進行記憶,有效處理具有重複引用和循環的複雜大型結構,透過避免冗餘克隆來確保最佳性能。 <a name="debounce"></a> `debounce()` ------------ ### 任務說明 重新建立`debounce`函數(來自“lodash”),它允許限制給定回調函數觸發的頻率。當在短時間內重複呼叫時,在指定的延遲後僅執行最後一次呼叫。 ``` function myDebounce(func, delay) { let timerId; const debounced = function(...args) { clearTimeout(timerId); timerId = setTimeout(() => { func.apply(this, args); }, delay); }; debounced.cancel = function() { clearTimeout(timerId); timerId = null; }; debounced.flush = function() { clearTimeout(timerId); func.apply(this, arguments); timerId = null; }; return debounced; } ``` ### 實施的關鍵面 1. **取消功能**:引入`.cancel`方法使外部控制能夠取消去抖函數的任何暫停執行。這增加了靈活性,允許響應特定事件或條件而取消去抖功能。 2. **透過 Flush 立即執行**: `.flush`方法允許立即執行去抖函數,而不考慮延遲。這在需要確保立即應用去抖函數的效果的情況下非常有用,例如,在卸載元件或完成互動之前。 <a name="throttle"></a> `throttle()` ------------ ### 任務說明 重新建立`throttle`函數(來自“lodash”),它確保給定的回調函數在每個指定的時間間隔內最多只呼叫一次(在我們的例子中是在開始時)。與去抖動不同,限制保證函數會定期執行,確保進行更新,儘管更新速度是受控的。 ### 執行 ``` function myThrottle(func, timeout) { let timerId = null; const throttled = function(...args) { if (timerId === null) { func.apply(this, args) timerId = setTimeout(() => { timerId = null; }, timeout) } } throttled.cancel = function() { clearTimeout(timerId); timerId = null; }; return throttled; } ``` ### 實施的關鍵面 1. **取消功能**:引入`.cancel`方法可以清除節流計時器的任何計劃重置。這在清理階段非常有用,例如 UI 庫/框架中的元件卸載,以防止過時的執行並有效管理資源。 <a name="promise"></a> `Promise` --------- ### 任務說明 重新建立`Promise`類別。它是為非同步程式設計的構造,允許暫停程式碼的執行,直到非同步進程完成。從本質上講,承諾代表了在其建立時不一定已知的值的代理。它允許您將處理程序與非同步操作的最終成功值或失敗原因相關聯。這使得非同步方法可以像同步方法一樣傳回值:非同步方法不是立即傳回最終值,而是傳回一個在未來某個時刻提供該值的承諾。 `Promise`包含處理已完成和拒絕狀態的方法( `then` 、 `catch` ),以及無論結果如何都執行程式碼的方法( `finally` )。 ``` class MyPromise { constructor(executor) { ... } then(onFulfilled, onRejected) { ... } catch(onRejected) { ... } finally(callback) { ... } } ``` ### `constructor`實現 ``` constructor(executor) { this.state = 'pending'; this.value = undefined; this.reason = undefined; this.onFulfilledCallbacks = []; this.onRejectedCallbacks = []; const resolve = (value) => { if (this.state === 'pending') { this.state = 'fulfilled'; this.value = value; this.onFulfilledCallbacks.forEach(fn => fn()); } }; const reject = (reason) => { if (this.state === 'pending') { this.state = 'rejected'; this.reason = reason; this.onRejectedCallbacks.forEach(fn => fn()); } }; try { executor(resolve, reject); } catch (error) { reject(error); } } ``` ### `constructor`實現的關鍵方面 1. **狀態管理**:以「待處理」狀態初始化。解決時切換為“已完成”,被拒絕時切換為“拒絕”。 2. **值和原因**:保存承諾的最終結果( `value` )或拒絕的原因( `reason` )。 - **處理非同步**:接受包含非同步操作的`executor`函數。 `executor`採用兩個函數, `resolve`和`reject` ,當呼叫它們時,將promise轉換到對應的狀態。 3. **回呼陣列**:維護回呼佇列( `onFulfilledCallbacks` 、 `onRejectedCallbacks` ),以用於等待解決或拒絕承諾的延遲操作。 ### `.then`實施 ``` resolvePromise(promise2, x, resolve, reject) { if (promise2 === x) { return reject(new TypeError( 'Chaining cycle detected for promise')); } if (x instanceof MyPromise) { x.then(resolve, reject); } else { resolve(x); } } then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value; onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason; }; let promise2 = new MyPromise((resolve, reject) => { if (this.state === 'fulfilled') { setTimeout(() => { try { let x = onFulfilled(this.value); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); } else if (this.state === 'rejected') { setTimeout(() => { try { let x = onRejected(this.reason); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); } else if (this.state === 'pending') { this.onFulfilledCallbacks.push(() => { setTimeout(() => { try { let x = onFulfilled(this.value); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); }); this.onRejectedCallbacks.push(() => { setTimeout(() => { try { let x = onRejected(this.reason); this.resolvePromise(promise2, x, resolve, reject); } catch (error) { reject(error); } }); }); } }); return promise2; } ``` ### `.then`實施的關鍵方面 1. **預設處理程序**:將非函數處理程序轉換為標識函數(用於實現)或拋出程序(用於拒絕),以確保承諾鏈中的正確轉發和錯誤處理。 2. **Promise 連結**: `then`方法允許連結 Promise,從而實現順序非同步操作。它會建立一個新的 Promise ( `promise2` ),該 Promise 取決於傳遞給它的回呼函數 ( `onFulfilled` 、 `onRejected` ) 的結果。 3. **處理解決方案和拒絕**:僅在當前承諾解決(履行或拒絕)後才會呼叫所提供的回調。每個回呼的結果 ( `x` ) 可能是一個值或另一個 Promise,決定了`promise2`的解析。 4. **防止連結循環**: `resolvePromise`函數檢查`promise2`是否與結果 ( `x` ) 相同,避免 Promise 等待自身的循環,從而導致`TypeError` 。 5. **支援 MyPromise 和 Non-Promise 值**:如果結果 ( `x` ) 是`MyPromise`的實例, `then`使用其解析或拒絕來解決`promise2` 。此功能支援基於 Promise 的操作的無縫集成,無論是來自`MyPromise`實例還是本機 JavaScript Promise,假設它們具有相似的行為。對於非 Promise 值,或當`onFulfilled`或`onRejected`只是傳回一個值時, `promise2`將使用該值進行解析,從而在 Promise 鏈中實現簡單的轉換或分支邏輯。 6. **非同步執行保證**:透過使用`setTimeout`延遲`onFulfilled`和`onRejected`的執行, `then`確保非同步為。此延遲保持一致的執行順序,確保`onFulfilled`和`onRejected`在執行堆疊清除後呼叫。 7. **錯誤處理**:如果`onFulfilled`或`onRejected`內發生異常, `promise2`會因錯誤而被拒絕,從而允許錯誤處理通過 Promise 鏈傳播。 ### `catch`並`finally`實現 ``` static resolve(value) { if (value instanceof MyPromise) { return value; } return new MyPromise((resolve, reject) => resolve(value)); } catch(onRejected) { return this.then(null, onRejected); } finally(callback) { return this.then( value => MyPromise.resolve(callback()) .then(() => value), reason => MyPromise.resolve(callback()) .then(() => { throw reason; }) ); } ``` ### `.catch`實施的關鍵面向: 1. **簡化的錯誤處理:** `.catch`方法是`.then(null, onRejected)`的簡寫,專門專注於處理拒絕場景。當只需要拒絕處理程序時,它允許更清晰的語法,從而提高程式碼的可讀性和可維護性。 2. **Promise Chaining 支援:**由於它在內部委託給`.then` ,所以`.catch`返回一個新的 Promise,從而保持 Promise 鏈功能。這允許在錯誤恢復或透過重新拋出或返回新的被拒絕的承諾傳播錯誤後繼續進行鏈操作。 3. **錯誤傳播:**如果提供了`onRejected`並且執行時沒有錯誤,則傳回的 Promise 將使用`onRejected`的傳回值進行解析,從而有效地允許 Promise 鏈中的錯誤復原。如果`onRejected`拋出錯誤或傳回被拒絕的 Promise,則錯誤會沿著鏈傳播。 ### `.finally`實現的關鍵面向: 1. **始終執行:** `.finally`方法確保執行提供的`callback` ,無論 Promise 是履行還是拒絕。這對於需要在非同步操作之後發生的清理操作特別有用,與其結果無關。 2. **傳回值保留:**雖然`.finally`中的`callback`不接收任何參數(與`.then`或`.catch`不同),但 Promise 的原始履行值或拒絕原因將被保留並透過鏈傳遞。從`.finally`傳回的 Promise 會以相同的值或原因被解析或拒絕,除非`callback`本身導致被拒絕的 Promise。 3. **錯誤處理與傳播:**如果`callback`執行成功, `.finally`傳回的 Promise 將按照與原始 Promise 相同的方式進行結算。但是,如果`callback`拋出錯誤或返回被拒絕的 Promise,則從`.finally`返回的 Promise 會因這個新錯誤而被拒絕,從而允許錯誤攔截並更改 Promise 鏈中的拒絕原因。 <a name="eventemitter"></a> `EventEmitter` -------------- ### 任務說明 重新建立`EventEmitter`類,該類別允許實現觀察者模式,使物件(稱為「發射器」)能夠發出命名事件,從而導致呼叫先前註冊的偵聽器(或「處理程序」)。這是 Node.js 中用於處理非同步事件的關鍵元件,廣泛用於發出訊號以及管理應用程式狀態和行為。實作自訂`EventEmitter`涉及建立用於註冊事件偵聽器、觸發事件和刪除偵聽器的方法。 ``` class MyEventEmitter { constructor() { this.events = {}; } on(eventName, listener) { if (!this.events[eventName]) { this.events[eventName] = []; } this.events[eventName].push(listener); } once(eventName, listener) { const onceWrapper = (...args) => { listener.apply(this, args); this.off(eventName, onceWrapper); }; this.on(eventName, onceWrapper); } emit(eventName, ...args) { const listeners = this.events[eventName]; if (listeners && listeners.length) { listeners.forEach((listener) => { listener.apply(this, args); }); } } off(eventName, listenerToRemove) { if (!this.events[eventName]) { return; } const filterListeners = (listener) => listener !== listenerToRemove; this.events[eventName] = this.events[eventName].filter(filterListeners); } } ``` ### `EventEmitter`實現的關鍵面 1. **EventListener Registration `.on` :**將偵聽器函數新增至指定事件的偵聽器陣列中,如果該事件名稱尚不存在則建立一個新陣列。 2. **一次性事件偵聽器`.once` :**註冊一個偵聽器,該偵聽器在呼叫一次後會自行刪除。它將原始偵聽器包裝在一個函數 ( `onceWrapper` ) 中,該函數也會在執行後刪除包裝器,確保偵聽器僅觸發一次。 3. **發出事件`.emit` :**觸發事件,使用提供的參數呼叫所有已註冊的偵聽器。它將參數應用於每個偵聽器函數,從而允許將資料傳遞給偵聽器。 4. **刪除事件偵聽器`.off` :**從事件偵聽器陣列中刪除特定偵聽器。如果事件在刪除後沒有偵聽器,則可以將其保留為空陣列或可選地進一步清理(此實作中未顯示)。 --- 原文出處:https://dev.to/antonzo/implementing-javascript-concepts-from-scratch-4623

如何建構:人工智慧驅動的部落格平台(Next.js、Langchain 和 Supabase)

**長話短說** -------- 在本文中,您將學習如何建立一個人工智慧驅動的部落格平台,該平台可以搜尋網路並研究部落格文章的任何主題。 我們將涵蓋: - 用於應用程式框架的 Next.js 🖥️ - 法學碩士 OpenAI 🧠 - LangChain 和 Tavily 的網路搜尋人工智慧代理🤖 - 使用 CopilotKit 將 AI 整合到您的應用程式中 🪁 - Supabase 用於儲存和檢索部落格平台文章資料。 --- CopilotKit:開源 Copilot 框架 ======================== CopilotKit 是[開源 AI 副駕駛框架和平台。](https://github.com/CopilotKit/CopilotKit)我們可以輕鬆地將強大的人工智慧整合到您的 React 應用程式中。 建造: - ChatBots💬:上下文感知的應用內聊天機器人,可以在應用程式內執行操作 - CopilotTextArea📝:人工智慧驅動的文字字段,具有上下文感知自動完成和插入功能 - 聯合代理🤖:應用程式內人工智慧代理,可以與您的應用程式和使用者互動。由浪鏈提供技術支援。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i8gltoave8490fg234ro.gif) {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} (原諒人工智慧的拼字錯誤並給一顆星:) 現在回到文章。 --- **先決條件** -------- 在開始建立應用程式之前,讓我們先查看建置應用程式所需的依賴項或套件 - `copilotkit/react-core` :CopilotKit 前端包,帶有 React hooks,用於向副駕駛提供應用程式狀態和操作(AI 功能) - `copilotkit/react-ui:`聊天機器人側邊欄 UI 的 CopilotKit 前端包 - `copilotkit/react-textarea:` CopilotKit 前端包,用於在演講者筆記中進行人工智慧輔助文字編輯。 - `LangChainJS:`用於開發由語言模型支援的應用程式的框架。 - `Tavily Search API:`幫助將法學碩士和人工智慧應用程式連接到可信賴的即時知識的 API。 安裝所有專案包和依賴項 ----------- 在安裝所有專案包和依賴項之前,我們首先在終端機上執行以下命令來建立 Nextjs 專案。 ``` npx create-next-app@latest ``` 然後系統會提示您選擇一些選項。請隨意標記它們,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1j04grq2jykx6o606u1s.png) 之後,使用您選擇的文字編輯器開啟新建立的 Nextjs 專案。然後在命令列中執行以下命令來安裝所有專案包和依賴項。 ``` npm i @copilotkit/backend @copilotkit/shared @langchain/langgraph @copilotkit/react-core @copilotkit/react-ui @copilotkit/react-textarea @supabase/ssr @supabase/auth-helpers-nextjs ``` **建立部落格平台前端** ------------- 在本節中,我將引導您完成使用靜態內容建立部落格平台前端的過程,以定義平台的使用者介面。 首先,前往`/[root]/src/app`並建立一個名為`components`的資料夾。在 Components 資料夾中,建立一個名為`Article.tsx`的檔案。 之後,將以下程式碼新增至定義名為`Article`功能元件的檔案中,該元件將用於呈現文章建立表單。 ``` "use client"; import { useRef, useState } from "react"; export function Article() { // Define state variables for article outline, copilot text, and article title const [articleOutline, setArticleOutline] = useState(""); const [copilotText, setCopilotText] = useState(""); const [articleTitle, setArticleTitle] = useState(""); return ( // Form element for article input <form action={""} className="w-full h-full gap-10 flex flex-col items-center p-10"> {/* Input field for article title */} <div className="flex w-full items-start gap-3"> <textarea className="p-2 w-full h-12 rounded-lg flex-grow overflow-x-auto overflow-y-hidden whitespace-nowrap" id="title" name="title" value={articleTitle} placeholder="Article Title" onChange={(event) => setArticleTitle(event.target.value)} /> </div> {/* Textarea for article content */} <textarea className="p-4 w-full aspect-square font-bold text-xl bg-slate-800 text-white rounded-lg resize-none" id="content" name="content" value={copilotText} placeholder="Write your article content here" onChange={(event) => setCopilotText(event.target.value)} /> {/* Publish button */} <button type="submit" className="p-4 w-full !bg-slate-800 text-white rounded-lg">Publish</button> </form> ); } ``` 接下來,將另一個檔案新增到元件資料夾中,並將其命名為`Header.tsx` 。然後將以下程式碼新增至定義名為`Header`的功能元件的檔案中,該元件將呈現部落格平台的導覽列。 ``` import Link from "next/link"; export default function Header() { return ( <> <header className="flex flex-wrap sm:justify-start sm:flex-nowrap z-50 w-full bg-white border-b border-gray-200 text-sm py-3 sm:py-0 "> <nav className="relative max-w-7xl w-full mx-auto px-4 sm:flex sm:items-center sm:justify-between sm:px-6 lg:px-8" aria-label="Global"> <div className="flex items-center justify-between"> <Link className="flex-none text-xl font-semibold " href="/" aria-label="Brand"> AIBlogging </Link> </div> <div id="navbar-collapse-with-animation" className=""> <div className="flex flex-col gap-y-4 gap-x-0 mt-5 sm:flex-row sm:items-center sm:justify-end sm:gap-y-0 sm:gap-x-7 sm:mt-0 sm:ps-7"> <Link className="flex items-center font-medium text-gray-500 border-2 border-indigo-600 text-center p-2 rounded-md hover:text-blue-600 sm:border-s sm:my-6 " href="/writearticle"> Create Post </Link> </div> </div> </nav> </header> </> ); } ``` 之後,轉到`/[root]/src/app`並建立一個名為`writearticle`的資料夾。在`writearticle`資料夾中,建立一個名為`page.tsx`檔案。然後將以下程式碼加入匯入`Article`和`Header`元件的檔案中。然後,程式碼定義了一個名為`WriteArticle`的功能元件,它將呈現導覽列和文章建立表單。 ``` import { Article } from "../components/Article"; import Header from "../components/Header"; export default function WriteArticle() { return ( <> <Header /> <Article /> </> ); } ``` 接下來,前往`/[root]/src/page.tsx`文件,並新增以下程式碼,該程式碼定義一個名為`Home`功能元件,該元件呈現將顯示已發佈文章清單的部落格平台主頁。 ``` import Image from "next/image"; import Link from "next/link"; import Header from "./components/Header"; const Home = async () => { return ( <> <Header /> <div className="max-w-[85rem] h-full px-4 py-10 sm:px-6 lg:px-8 lg:py-14 mx-auto"> <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6"> <Link key={""} className="group flex flex-col h-full bg-white border border-gray-200 hover:border-transparent hover:shadow-lg transition-all duration-300 rounded-xl p-5 " href={""}> <div className="aspect-w-16 aspect-h-11"> <Image className="object-cover h-48 w-96 rounded-xl" src={`https://source.unsplash.com/featured/?${encodeURIComponent( "hello world" )}`} width={500} height={500} alt="Image Description" /> </div> <div className="my-6"> <h3 className="text-xl font-semibold text-gray-800 "> Hello World </h3> </div> </Link> </div> </div> </> ); }; export default Home; ``` 之後,請轉到`next.config.js`檔案並加入以下程式碼,該程式碼允許您使用 Unsplash 中的圖像作為已發布文章的封面圖像。 ``` module.exports = { images: { remotePatterns: [ { protocol: "https", hostname: "source.unsplash.com", }, ], }, }; ``` 最後,在命令列上執行命令`npm run dev` ,然後導航到 http://localhost:3000/。現在您應該在瀏覽器上查看部落格平台前端,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m319h0j3ta0xa1fhkezo.png) **將部落格平台與 CopilotKit 後端集成** --------------------------- 在本節中,我將引導您完成將部落格平台與 CopilotKit 後端整合的過程,CopilotKit 後端處理來自前端的請求,提供函數呼叫和各種 LLM 後端(例如 GPT)。此外,我們將整合一個名為 Tavily 的人工智慧代理,它可以研究網路上的任何主題。 首先,在根目錄中建立一個名為`.env.local`的檔案。然後在保存`ChatGPT`和`Tavily` Search API 金鑰的檔案中加入下面的環境變數。 ``` OPENAI_API_KEY="Your ChatGPT API key" TAVILY_API_KEY="Your Tavily Search API key" ``` 若要取得 ChatGPT API 金鑰,請導覽至 https://platform.openai.com/api-keys。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/co9getwdzh34u1k5cehf.png) 若要取得 Tavilly Search API 金鑰,請導覽至 https://app.tavily.com/home ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ju9syhy5w8oip67tyne0.png) 之後,轉到`/[root]/src/app`並建立一個名為`api`的資料夾。在`api`資料夾中,建立一個名為`copilotkit`的資料夾。在`copilotkit`資料夾中,建立一個名為`research.ts`的檔案。然後導航到[該 Research.ts gist 文件](https://gist.github.com/TheGreatBonnie/58dc21ebbeeb8cbb08df665db762738c),複製程式碼,並將其新增至**`research.ts`**檔案中 接下來,在`/[root]/src/app/api/copilotkit`資料夾中建立一個名為`route.ts`的檔案。該文件將包含設定後端功能來處理 POST 請求的程式碼。它有條件地包括對給定主題進行研究的“研究”操作。 現在在文件頂部導入以下模組。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; // For backend functionality with CopilotKit. import { researchWithLangGraph } from "./research"; // Import a custom function for conducting research. import { AnnotatedFunction } from "@copilotkit/shared"; // For annotating functions with metadata. ``` 在上面的程式碼下面,定義一個執行時間環境變數和一個名為`researchAction`的函數,該函數使用下面的程式碼對某個主題進行研究。 ``` // Define a runtime environment variable, indicating the environment where the code is expected to run. export const runtime = "edge"; // Define an annotated function for research. This object includes metadata and an implementation for the function. const researchAction: AnnotatedFunction<any> = { name: "research", // Function name. description: "Call this function to conduct research on a certain topic. Respect other notes about when to call this function", // Function description. argumentAnnotations: [ // Annotations for arguments that the function accepts. { name: "topic", // Argument name. type: "string", // Argument type. description: "The topic to research. 5 characters or longer.", // Argument description. required: true, // Indicates that the argument is required. }, ], implementation: async (topic) => { // The actual function implementation. console.log("Researching topic: ", topic); // Log the research topic. return await researchWithLangGraph(topic); // Call the research function and return its result. }, }; ``` 然後在上面的程式碼下加入下面的程式碼來定義處理POST請求的非同步函數。 ``` // Define an asynchronous function that handles POST requests. export async function POST(req: Request): Promise<Response> { const actions: AnnotatedFunction<any>[] = []; // Initialize an array to hold actions. // Check if a specific environment variable is set, indicating access to certain functionality. if (process.env["TAVILY_API_KEY"]) { actions.push(researchAction); // Add the research action to the actions array if the condition is true. } // Instantiate CopilotBackend with the actions defined above. const copilotKit = new CopilotBackend({ actions: actions, }); // Use the CopilotBackend instance to generate a response for the incoming request using an OpenAIAdapter. return copilotKit.response(req, new OpenAIAdapter()); } ``` **將部落格平台與 CopilotKit 前端集成** --------------------------- 在本節中,我將引導您完成將部落格平台與 CopilotKit 前端整合的過程,以促進部落格文章研究和文章大綱生成。我們將使用聊天機器人側欄元件、copilot 文字區域元件、用於向 Copilot 提供應用程式狀態和其他資訊的 useMakeCopilotReadable 掛鉤,以及用於提供 Copilot 可以呼叫的操作的 useCopilotAction 掛鉤 首先,導入`/[root]/src/app/components/Article.tsx`檔案頂部的`useMakeCopilotReadable` 、 `useCopilotAction` 、 `CopilotTextarea`和`HTMLCopilotTextAreaElement`掛鉤。 ``` import { useMakeCopilotReadable, useCopilotAction, } from "@copilotkit/react-core"; import { CopilotTextarea, HTMLCopilotTextAreaElement, } from "@copilotkit/react-textarea"; ``` 在 Article 函數內的狀態變數下方,新增以下程式碼,該程式碼使用`useMakeCopilotReadable`掛鉤來新增將作為應用程式內聊天機器人的上下文產生的文章大綱。鉤子使副駕駛可以閱讀文章大綱。 ``` useMakeCopilotReadable("Blog article outline: " + JSON.stringify(articleOutline)); ``` 在`useMakeCopilotReadable`掛鉤下方,使用以下程式碼建立一個名為`copilotTextareaRef`的引用,該引用指向名為`HTMLCopilotTextAreaElement`的文字區域元素。 ``` const copilotTextareaRef = useRef<HTMLCopilotTextAreaElement>(null); ``` 在上面的程式碼下方,加入以下程式碼,該程式碼使用`useCopilotAction`掛鉤來設定名為`researchBlogArticleTopic`的操作,該操作將啟用對部落格文章的給定主題的研究。此操作採用兩個參數,稱為`articleTitle`和`articleOutline` ,這兩個參數可以產生文章標題和大綱。 該操作包含一個處理程序函數,該函數根據給定主題生成文章標題和大綱。在處理函數內部, `articleOutline`狀態會使用新產生的大綱進行更新,而`articleTitle`狀態會使用新產生的標題進行更新,如下所示。 ``` useCopilotAction( { name: "researchBlogArticleTopic", description: "Research a given topic for a blog article.", parameters: [ { name: "articleTitle", type: "string", description: "Title for a blog article.", required: true, }, { name: "articleOutline", type: "string", description:"Outline for a blog article that shows what the article covers.", required: true, }, ], handler: async ({ articleOutline, articleTitle }) => { setArticleOutline(articleOutline); setArticleTitle(articleTitle); }, }, [] ); ``` 在上面的程式碼下方,前往表單元件並新增以下`CopilotTextarea`元素,該元素將使您能夠為文章內容新增補全、插入和編輯。 ``` <CopilotTextarea value={copilotText} ref={copilotTextareaRef} placeholder="Write your article content here" onChange={(event) => setCopilotText(event.target.value)} className="p-4 w-full aspect-square font-bold text-xl bg-slate-800 text-white rounded-lg resize-none" placeholderStyle={{ color: "white", opacity: 0.5, }} autosuggestionsConfig={{ textareaPurpose: articleTitle, chatApiConfigs: { suggestionsApiConfig: { forwardedParams: { max_tokens: 5, stop: ["\n", ".", ","], }, }, insertionApiConfig: {}, }, debounceTime: 250, }} /> ``` 然後將Tailwindcss隱藏類別加入文章內容的Textarea中,如下所示。文字區域將保存文章的內容,並在文章發布後將其插入資料庫。 ``` {/* Textarea for article content */} <textarea className="p-4 w-full aspect-square font-bold text-xl bg-slate-800 text-white rounded-lg resize-none hidden" id="content" name="content" value={copilotText} placeholder="Write your article content here" onChange={(event) => setCopilotText(event.target.value)} /> ``` 之後,請前往`/[root]/src/app/writearticle/page.tsx`檔案並使用下面的程式碼匯入頂部的 CopilotKit 前端套件和樣式。 ``` import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import "@copilotkit/react-ui/styles.css"; import "@copilotkit/react-textarea/styles.css"; ``` 然後使用`CopilotKit`和`CopilotSidebar`包裹Article元件,如下所示。 `CopilotKit`元件指定 CopilotKit 後端端點 ( `/api/copilotkit/openai/` ) 的 URL,而`CopilotSidebar`則呈現應用程式內聊天機器人,您可以提示您研究文章的任何主題。 ``` export default function WriteArticle() { return ( <> <Header /> <CopilotKit url="/api/copilotkit"> <CopilotSidebar instructions="Help the user research a blog article topic." defaultOpen={true} labels={{ title: "Blog Article Copilot", initial: "Hi you! 👋 I can help you research any topic for a blog article.", }} clickOutsideToClose={false}> <Article /> </CopilotSidebar> </CopilotKit> </> ); } ``` 之後,執行開發伺服器並導航到 http://localhost:3000/writearticle。您應該會看到應用程式內聊天機器人已整合到部落格平台中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yx7m6fhxm9gdg942a0sq.png) 給右側的聊天機器人一個提示,例如“研究一篇關於生成人工智慧的部落格文章主題,然後給我文章大綱。”聊天機器人將開始研究該主題,然後產生部落格標題。 當您開始在編輯器上寫作時,您應該會看到內容自動建議,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ocnhptqxnk5gopvlzfs8.png) **將部落格平台與 Supabase 資料庫集成** -------------------------- 在本節中,我將引導您完成將部落格平台與 Supabase 資料庫整合以插入和獲取部落格文章資料的過程。 首先,導覽至[supabase.com](http://supabase.com)並點擊主頁上的「啟動您的專案」按鈕。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/95n06a6aj55r5w959gz6.png) 然後新建一個專案,名為AiBloggingPlatform,如下圖所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lifhztowgy3g1v9wwnjk.png) 建立專案後,將 Supabase URL 和 API 金鑰新增至 env.local 檔案中的環境變數中,如下所示。 ``` NEXT_PUBLIC_SUPABASE_URL=”Your Supabase URL” NEXT_PUBLIC_SUPABASE_ANON_KEY=”Your Supabase API Key” ``` 之後,請前往 Supabase 上專案的儀表板並開啟 SQL 編輯器部分。然後將下列 SQL 程式碼新增至編輯器中,然後按一下 CTRL + Enter 鍵建立一個名為articles 的表。文章表包含 id、標題和內容行。 ``` create table if not exists articles ( id bigint primary key generated always as identity, title text, content text ); ``` 建立表格後,您應該會收到一條成功訊息,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bjb84czwivk6ue7duj0b.png) 之後,轉到`/[root]/src/`資料夾並建立一個名為`utils`的資料夾。在`utils`資料夾內,建立一個名為`supabase.ts`文件,並新增以下用於建立並傳回 Supabase 用戶端的程式碼。 ``` // Importing necessary functions and types from the Supabase SSR package import { createServerClient, type CookieOptions } from '@supabase/ssr' // Define a function named 'supabase' that takes a 'CookieOptions' object as input export const supabase = (cookies: CookieOptions) => { // Retrieve cookies from the provided 'CookieOptions' object const cookieStore = cookies() // Create and return a Supabase client configured with environment variables and cookie handling return createServerClient( // Retrieve Supabase URL from environment variables process.env.NEXT_PUBLIC_SUPABASE_URL!, // Retrieve Supabase anonymous key from environment variables process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, { cookies: { // Define a custom 'get' function to retrieve cookies by name from the cookie store get(name: string) { return cookieStore.get(name)?.value }, }, } ) } ``` 然後轉到`/[root]/src/app`資料夾並建立一個名為`serveractions`的資料夾。在`serveractions`資料夾中,建立一個名為`AddArticle.ts`的文件,並新增以下程式碼,將部落格文章資料插入到 Supabase 資料庫中。 ``` // Importing necessary functions and modules for server-side operations "use server"; import { createServerComponentClient } from "@supabase/auth-helpers-nextjs"; import { cookies } from "next/headers"; import { redirect } from "next/navigation"; // Define an asynchronous function named 'addArticle' that takes form data as input export async function addArticle(formData: any) { // Extract title and content from the provided form data const title = formData.get("title"); const content = formData.get("content"); // Retrieve cookies from the HTTP headers const cookieStore = cookies(); // Create a Supabase client configured with the provided cookies const supabase = createServerComponentClient({ cookies: () => cookieStore }); // Insert the article data into the 'articles' table on Supabase const { data, error } = await supabase.from("articles").insert([ { title, content, }, ]); // Check for errors during the insertion process if (error) { console.error("Error inserting data", error); return; } // Redirect the user to the home page after successfully adding the article redirect("/"); // Return a success message return { message: "Success" }; } ``` 之後,轉到`/[root]/src/app/components/Article.tsx`檔案並導入`addArticle`函數。 ``` import { addArticle } from "../serveractions/AddArticle"; ``` 然後加入`addArticle`函數作為表單動作參數,如下所示。 ``` // Form element for article input <form action={addArticle} className="w-full h-full gap-10 flex flex-col items-center p-10"> </form> ``` 之後,導覽至http://localhost:3000/writearticle,研究您選擇的主題,新增文章內容,然後點擊底部的發布按鈕來發布文章。 然後轉到 Supabase 上專案的儀表板並導航到表編輯器部分。您應該會看到您的文章資料已插入 Supabase 資料庫,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fklcuyv5q5eq1ajmdjyv.png) 接下來,前往`/[root]/src/app/page.tsx`檔案並在頂部導入 cookie 和 supabase 套件。 ``` import { cookies } from "next/headers"; import { supabase } from "@/utils/supabase"; ``` 然後在 Home 函數中加入以下程式碼,從 Supabase 資料庫中取得文章資料。 ``` const { data: articles, error } = await supabase(cookies).from('articles').select('*') ``` 之後,更新如下所示的元素程式碼,以將已發佈的文章呈現在部落格平台主頁上。 ``` return ( <> <Header /> <div className="max-w-[85rem] h-full px-4 py-10 sm:px-6 lg:px-8 lg:py-14 mx-auto"> <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-6"> {articles?.map((post: any) => ( <Link key={post.id} className="group flex flex-col h-full bg-white border border-gray-200 hover:border-transparent hover:shadow-lg transition-all duration-300 rounded-xl p-5 " href={`/posts/${post.id}`}> <div className="aspect-w-16 aspect-h-11"> <Image className="object-cover h-48 w-96 rounded-xl" src={`https://source.unsplash.com/featured/?${encodeURIComponent( post.title )}`} width={500} height={500} alt="Image Description" /> </div> <div className="my-6"> <h3 className="text-xl font-semibold text-gray-800 "> {post.title} </h3> </div> </Link> ))} </div> </div> </> ); ``` 然後導航到[http://localhost:3000](http://localhost:3000/writearticle) ,您應該會看到您發布的文章,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/429bilwyje2a4xh0il5n.png) 之後,轉到`/[root]/src/app`資料夾並建立一個名為`[id].`在`[id]`資料夾中,建立一個名為`page.tsx`的文件,並在頂部匯入以下套件和元件。 ``` import { supabase } from '@/utils/supabase'; import { cookies } from "next/headers"; import Header from '@/app/components/Header'; ``` 在導入下面,定義一個名為「getArticles」的非同步函數,該函數根據 id 參數從 supabase 資料庫檢索文章資料,如下所示。 ``` // Define an asynchronous function named 'getArticles' that retrieves article data based on the provided parameters async function getArticles(params: any) { // Extract the 'id' parameter from the provided 'params' object const { id } = params // Retrieve article data from Supabase database where the 'id' matches the provided value const { data, error } = await supabase(cookies) .from('articles') .select('*') .eq('id', id) .single(); // Return the retrieved data return data } ``` 在上面的程式碼下面,定義一個名為“Post”的函數,它將“params”作為 props,如下所示。 ``` // Define a default asynchronous function named 'Post' that takes 'params' as props export default async function Post({ params }: { params: any }) { // Retrieve the post data asynchronously based on the provided 'params' const post = await getArticles(params); // Return JSX to render the post details return ( <> {/* Render the header component */} <Header /> {/* Main content wrapper */} <div className="max-w-3xl px-4 pt-6 lg:pt-10 pb-12 sm:px-6 lg:px-8 mx-auto"> <div className="max-w-2xl"> <div className="space-y-5 md:space-y-8"> <div className="space-y-3"> {/* Render the post title */} <h2 className="text-2xl font-bold md:text-3xl dark:text-white"> {/* Render the post title only if 'post' is truthy */} {post && post.title} </h2> {/* Render the post content */} <p className="text-lg text-gray-800 dark:text-gray-200"> {/* Render the post content only if 'post' is truthy */} {post && post.content} </p> </div> </div> </div> </div> </> ); } ``` 之後,導覽至[http://localhost:3000](http://localhost:3000/writearticle)並點擊部落格平台主頁上顯示的文章。 然後您應該被重定向到文章的內容,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ojie4iwb8qn56gd2a907.png) 結論 -- 總而言之,您可以使用 CopilotKit 建立應用內 AI 聊天機器人,該機器人可以查看當前應用程式狀態並在應用程式內執行操作。 AI 聊天機器人可以與您的應用程式前端、後端和第三方服務對話。 完整的原始碼:https://github.com/TheGreatBonnie/aipoweredblog --- 原文出處:https://dev.to/copilotkit/how-to-build-an-ai-powered-blogging-platform-nextjs-langchain-supabase-1hdp

終於有人修復了 Javascript

JavaScript 生態系統正以驚人的速度發展。當您熟悉某種技術時,就會出現大量新方法。其中一些(例如 TypeScript)獲得了廣泛採用,而另一些(例如 CoffeeScript)則悄悄消失。每項創新最初都會引起人們的興奮,但隨著時間的推移,社區經常分裂,批評者最終會產生自己的框架。這種無止盡的循環讓我對聲稱可以解決所有問題的最新「神奇」框架越來越警惕。我已經從尋求工具作為解決方案轉變為擁抱對模式的理解,而不是不斷追求新技術。 這就是為什麼我向您指出針對 TypeScript 專案的特殊工具,不僅僅是另一個工具,而是鼓勵良好實踐的範例: [Effect](https://effect.website/) 。 讓我們來看看為什麼你應該踏出這一步。 彩色函數 ---- 您是否曾經問過自己,[您的功能是什麼顏色?](https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/) 讓我為您總結一下。想像一下您的程式碼庫中有藍色和紅色函數。規則很簡單:您可以在藍色函數中使用紅色函數,但反之則不行。那不是一場惡夢嗎?現在用“async”替換藍色。是的,你在 Javascript 得到了函數著色。 那我們該如何對抗這種著色問題呢?如果我們想刪除彩色函數,我們需要建立某種包裝器,僅在需要時使用 Promise。例如「未來」還是…「效果」? ``` import { Effect, pipe } from "effect"; const fibonacci = (a: number): Effect.Effect<number> => a <= 1 ? Effect.succeed(a) : pipe( Effect.all([fibonacci(a - 1), fibonacci(a - 2)]), Effect.map(([a, b]) => a + b) ); await Effect.runPromise(fibonacci(10)); ``` 使用`Effect`與`Promise`主要差異在於如何處理並發。 Effect 提供了 Fiber,它是類似於綠色線程或 goroutine 的輕量級並發結構。此功能允許我們在不阻塞主執行緒的情況下執行長時間執行或非同步任務,即使在傳統的同步函數中也可以啟動主執行緒。 ``` import { Effect, Console, pipe } from "effect"; const longRunningTask = pipe( Console.log("Start of long running task"), Effect.delay(1000), Effect.tap(Console.log("End of long running task")) ); console.log("Start of program"); Effect.runFork(longRunningTask); console.log("End of program"); /** * OUTPUT: * Start of program * End of program * Start of long running task * End of long running task */ ``` 雖然Effect 並沒有消除JavaScript 中固有的非同步/同步差異(函數著色),但透過使用纖程處理非同步操作,它允許同步函數呼叫非同步效果,而不會使其本身成為非同步,從而在很大程度上緩解“著色”問題。 類型安全錯誤 ------ 我們來看看這個函數: ``` const divide = (a: number, b: number) => a / b; ``` 我們這裡剛剛引入了一個問題,我們不能除以零。那麼讓我們稍微重構一下程式碼: ``` const divide = (a: number, b: number) => { if (b === 0) throw new Error('Cannot divide by zero.'); return a / b; } ``` 你覺得不錯嗎?它不是。因為它不是類型安全的。想要使用您的函數的人不會知道您的函數可能會拋出異常。對於像這樣的簡單函數來說,這可能看起來微不足道,但是當您有數十個潛在錯誤時,它可能會變成一場噩夢。其他較成熟的語言有諸如`Either`或`Result`之類的概念來表示類型安全錯誤。看起來像這樣: ``` type Result<T, E> = Ok<T> | Err<E>; // With something like: type Ok<T> = { kind: "Ok", data: T }; type Err<E> = { kind: "Err", err: E }; ``` 使用 Effect,您將擁有開箱即用的功能: `Effect<T, E>` 。您不必問自己在執行過程中會發生什麼樣的錯誤,您可以直接從函數簽名中知道它。它還附帶幫助函數來從錯誤中恢復。 ``` const divide = (a: number, b: number): Effect<number, "DivisionByZeroError"> => { if (b === 0) return Effect.fail("DivisionByZeroError"); return Effect.succeed(a / b); } ``` 新類型或品牌類型 -------- 你知道,回顧我以前的職能,我意識到我們可以做得更好。 ``` const divide = (a: number, b: NonZeroNumber) => ... ``` 那麼如何定義`NonZeroNumber`呢?如果您只是`type NonZeroNumber = number`它不會阻止人們用「0」來呼叫它。有一個模式:新類型。是的,Effect 也支持這一點: ``` import { Brand } from "effect" type NonZeroNumber = number & Brand.Brand<"NonZeroNumber"> const NonZeroNumber = Brand.refined<NonZeroNumber>( (n) => n !== 0, // Check if the value is a non-zero number (n) => Brand.error(`Expected ${n} to be a non-zero number`) ) ``` 這樣,您就知道您的函數**不能**使用任何數字來呼叫:它需要一種不包括零的特殊類型的數字。 依賴注入 ---- 如果您想遵循「控制反轉」原則,您可能需要研究「依賴注入」。這個概念非常簡單:函數應該能夠從自己的上下文中存取它所需要的內容。 ``` // With a singleton const read = (filename) => FileReader.read(filename); // With dependency injection const read = (reader: FileReader) => (filename) => reader.read(filename); ``` 出於多種原因,最好這樣做,例如解耦事物、允許輕鬆測試、具有不同的上下文等。 雖然有幾個框架可以幫助實現這一點,但 Effect 確實透過簡化來粉碎它:將依賴項作為 Effect 的第三個參數。 ``` const read = (filename): Effect<File, Error, FileReader> => { return Effect.flatMap(FileReader, fileReader => { return fileReader.read(filename); }) } ``` 結論 -- 您應該考慮 Effect 的原因還有很多。當然,一開始並不容易,您必須學習以不同的方式編碼。但與許多讓你學習「他們的」做事方式的框架相反,Effect 實際上教你好的模式,這些模式已經在其他語言中得到了證明。實際上,Effect 很大程度上受到了 Scala 中的 ZIO 的啟發,而 Scala 本身也受到了 Haskell 的啟發,而 Haskell 至今仍被認為是良好程式模式的頂峰之一。 --- 原文出處:https://dev.to/almaju/someone-finally-fixed-javascript-426i

21 個正在改變世界的人工智慧工具

世界上充滿了有前景的人工智慧工具,如 Sora、ChatGPT 以及更多即將推出的工具。 我收集了一些你必須使用的令人興奮的人工智慧工具。 該清單包括 Devin AI 的開源替代品、Notion、5 秒內的語音克隆、電子郵件自動化軟體以及您從未聽說過的工具。好奇心超載! 別忘了給他們加星號🌟 讓我們涵蓋這一切! --- 1. [Taipy](https://github.com/Avaiga/taipy) - 將資料和人工智慧演算法整合到生產就緒的 Web 應用程式中。 ---------------------------------------------------------------------------- ![打字](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/deak7rre409rzv5j5viv.png) Taipy 是一個開源 Python 庫,可用於輕鬆的端到端應用程式開發,具有假設分析、智慧管道執行、內建調度和部署工具。 我相信你們大多數人都不明白 Taipy 用於為基於 Python 的應用程式建立 GUI 介面並改進資料流管理。 因此,您可以繪製資料集的圖表,並使用類似 GUI 的滑桿來提供使用其他實用功能來處理資料的選項。 雖然 Streamlit 是一種流行的工具,但在處理大型資料集時,其效能可能會顯著下降,這使得它在生產級使用上不切實際。 另一方面,Taipy 在不犧牲性能的情況下提供了簡單性和易用性。透過嘗試 Taipy,您將親身體驗其用戶友好的介面和高效的資料處理。 在底層,Taipy 利用各種函式庫來簡化開發並增強功能。 ![圖書館](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n9xts3nof4uapr7dakrl.png) 開始使用以下命令。 ``` pip install taipy ``` 我們來談談最新的[Taipy v3.1 版本](https://docs.taipy.io/en/latest/relnotes/)。 最新版本使得在 Taipy 的多功能零件物件中可視化任何 HTML 或 Python 物件成為可能。 這意味著[Folium](https://python-visualization.github.io/folium/latest/) 、 [Bokeh](https://bokeh.org/) 、 [Vega-Altair](https://altair-viz.github.io/)和[Matplotlib](https://matplotlib.org/)等程式庫現在可用於視覺化。 這也帶來了對[Plotly python](https://plotly.com/python/)的原生支持,使繪製圖表變得更加容易。 ![陰謀蟒蛇](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdewvex88md09hvu3s80.png) 他們還使用分散式運算提高了效能,但最好的部分是 Taipy,它的所有依賴項現在都與 Python 3.12 完全相容,因此您可以在使用 Taipy 進行專案的同時使用最新的工具和程式庫。 您可以閱讀[文件](https://docs.taipy.io/en/latest/)。 例如,您可以看到[聊天演示](https://docs.taipy.io/en/release-3.1/gallery/llm/5_chatbot/),它使用 OpenAI 的 GPT-4 API 來產生對您的訊息的回應。您可以輕鬆更改程式碼以使用任何其他 API 或模型。 ![聊天演示](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kug1mclhmzyad0hjchif.png) 另一個有用的事情是,Taipy 團隊提供了一個名為[Taipy Studio](https://docs.taipy.io/en/latest/manuals/studio/)的 VSCode 擴充功能來加速 Taipy 應用程式的建置。 ![太皮工作室](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kc1umm5hcxes0ydbuspb.png) 您也可以使用 Taipy 雲端部署應用程式。 如果您想閱讀部落格來了解程式碼庫結構,您可以閱讀 HuggingFace[的使用 Taipy 在 Python 中為您的 LLM 建立 Web 介面](https://huggingface.co/blog/Alex1337/create-a-web-interface-for-your-llm-in-python)。 嘗試新技術通常很困難,但 Taipy 提供了[10 多個演示教程,](https://docs.taipy.io/en/release-3.1/gallery/)其中包含程式碼和適當的文件供您遵循。 例如,一些現場演示範例和專案想法: - [新冠儀表板](https://covid-dashboard.taipy.cloud/Country) - [推文生成](https://tweet-generation.taipy.cloud/) - [資料視覺化](https://production-planning.taipy.cloud/Data-Visualization) - [即時人臉辨識](https://face-recognition.taipy.cloud/) - [國際象棋大師](https://github.com/KorieDrakeChaney/taipy-chess) Taipy 在 GitHub 上有 7k+ Stars,並且處於`v3`版本,因此它們正在不斷改進。 https://github.com/Avaiga/taipy Star Taipy ⭐️ --- 2. [PR Agent](https://github.com/Codium-ai/pr-agent) - 自動拉取請求分析、回饋、建議的工具。 ------------------------------------------------------------------------- ![公關代理](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6sq9u9ktdhdu4pax9u7i.gif) 這是一個開源工具,可幫助有效地審查和處理拉取請求。它有許多獨特的選項,並提供跨各種 git 提供者的廣泛的拉取請求功能。 每天有數百萬個開源專案和數百個 Pull 請求,因此有一個可以幫助您的朋友是非常好的事情。 我是開源維護者,所以我知道有時會變得多麼困難,特別是每天都要審查這麼多的 Pull 請求。 無論如何,這就是公關代理商的幕後工作方式。 ![建築學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kkd9vxxqhu99f2elv8c.png) 您必須使用`@CodiumAI-Agent /review`對拉取請求發表評論,代理商將透過對 PR 的審查進行回應。有很多可用的選項,例如`describe`和`improve` 。 他們也提供了 [PR-Agent 工具](https://pr-agent-docs.codium.ai/tools/),每個頁面都有一個專門的頁面來解釋如何使用它。 您可以閱讀[文件](https://pr-agent-docs.codium.ai/installation/)並查看[範例結果](https://github.com/Codium-ai/pr-agent?tab=readme-ov-file#example-results)。 最好的部分是您甚至可以將其作為[GitHub Action](https://pr-agent-docs.codium.ai/installation/github/#run-as-a-github-action)執行。他們還提供了一個專業版本,有更多的選擇,但免費套餐足以開始使用。 如果您正在尋找好的文章,我推薦[使用 CodiumAI PR-Agent 自動進行拉取請求審查和](https://rnemet.dev/posts/ai/codium-pragent/)[CodiumAI PR-Agent 讓開發人員的生活更輕鬆的 5 個原因](https://medium.com/@mengineer/5-reasons-why-codiumai-pr-agent-is-making-developers-lives-easier-e040be0f6a36)。這些提供了有關 PR Agent 的大量概述。 它們在 GitHub 上有大約 3800 個 Star,被 300 多名開發人員使用,並且是使用 Python 建構的。雖然它們可能不是非常受歡迎,但它們的用例非常好。 https://github.com/Codium-ai/pr-agent 明星公關代理人 ⭐️ --- 3. [Mintlify](https://github.com/mintlify/writer) - 在建置時出現的文件。 -------------------------------------------------------------- ![精簡](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gvk07kmn8p48cpssogov.png) Mintlify 是一款由人工智慧驅動的文件編寫器,您只需 1 秒鐘即可編寫程式碼文件 :D 幾個月前我發現了 Mintlify,從那時起我就一直是它的粉絲。我見過很多公司使用它,甚至我使用我的商務電子郵件產生了完整的文件,結果證明這是非常簡單和體面的。如果您需要詳細的文件,Mintlify 就是解決方案。 另一個用例是根據我們將在這裡討論的程式碼產生文件。 您可以安裝[VSCode 擴充功能](https://marketplace.visualstudio.com/items?itemName=mintlify.document)或將其安裝在[IntelliJ](https://plugins.jetbrains.com/plugin/18606-mintlify-doc-writer)上。 您只需突出顯示程式碼或將遊標放在要記錄的行上。然後點選「編寫文件」按鈕(或按 ⌘ + 。) 您可以閱讀[文件](https://github.com/mintlify/writer?tab=readme-ov-file#%EF%B8%8F-mintlify-writer)和[安全指南](https://writer.mintlify.com/security)。 如果您更喜歡教程,那麼您可以觀看[Mintlify 的工作原理](https://www.loom.com/embed/3dbfcd7e0e1b47519d957746e05bf0f4)。它支援 10 多種程式語言,並支援許多文件字串格式,例如 JSDoc、reST、NumPy 等。 順便說一句,他們的網站連結是[writer.mintlify.com](https://writer.mintlify.com/) ;回購協議中目前的似乎是錯誤的。 它在 GitHub 上有大約 2.4k 顆星,受到許多開發人員的喜愛,並且是使用 TypeScript 建構的。 https://github.com/mintlify/writer Star Mintlify ⭐️ --- 4.[螢幕截圖到程式碼](https://github.com/abi/screenshot-to-code)- 放入螢幕截圖並將其轉換為乾淨的程式碼。 --------------------------------------------------------------------------- ![截圖到程式碼](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5akiyz5telxqqsj32ftu.png) 這是一個非常受歡迎的開源專案,但我可以肯定地說,很多開發人員仍然沒有意識到這一點。使用此功能,您可以將使用者介面的建置速度提高 10 倍。 這是一個簡單的工具,可以使用 AI 將螢幕截圖、模型和 Figma 設計轉換為乾淨、實用的程式碼。 該應用程式有一個 React/Vite 前端和一個 FastAPI 後端。如果您想使用 Claude Sonnet 或實驗性視訊支持,您將需要一個能夠存取 GPT-4 Vision API 的 OpenAI API 金鑰或一個 Anthropic 金鑰。您可以閱讀[指南](https://github.com/abi/screenshot-to-code?tab=readme-ov-file#-getting-started)來開始。 您可以在託管版本上[即時試用](https://screenshottocode.com/),並觀看 wiki 上提供的[一系列演示影片](https://github.com/abi/screenshot-to-code/wiki/Screen-Recording-to-Code)。 他們在 GitHub 上擁有超過 47k 顆星星,並支援許多技術堆疊,例如 React 和 Vue,以及不錯的 AI 模型,例如 GPT-4 Vision、Claude 3 Sonnet 和 DALL-E 3。 https://github.com/abi/screenshot-to-code 將螢幕截圖轉為程式碼 ⭐️ --- 5. [FaceSwap](https://github.com/deepfakes/faceswap) - 適合所有人的 Deepfakes 軟體。 --------------------------------------------------------------------------- ![換臉](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ps8nidwchglscdrk0117.png) 我總是對 Deepfakes 著迷,因為這就是某些人工智慧的工作原理,尤其是使用影片的人工智慧。 相信我!我們中的許多人甚至不使用它來建立影片,我們只是修改程式碼來看看它的作用,不道德的使用並不能代表它的建立原因、我們現在如何使用它,或者我們對它的未來的看法。 您應該觀看此影片以了解電腦如何辨識臉!觀看[此影片](https://www.youtube.com/watch?v=aircAruvnKk)以了解神經網路的基本功能。 https://www.youtube.com/watch?v=R9OHn5ZF4Uo 您可以閱讀[INSTALL.md](https://github.com/deepfakes/faceswap/blob/master/INSTALL.md)以取得詳細的安裝指南。根據文件,您需要具有 CUDA 支援的現代 GPU 才能獲得最佳效能。許多 AMD GPU 透過 DirectML (Windows) 和 ROCm (Linux) 支援。 您可以閱讀<a href="">文件</a>、觀看[演示影片](https://www.dailymotion.com/video/x810mot)並存取他們的[部落格](https://faceswap.dev/blog/)以觀看具有其他用例的會議影片。 我最喜歡的事實是,他們有一個非常簡單的部分,介紹任何人如何為該專案做出貢獻,包括對生成模型感興趣的人、開發人員、非開發高級用戶、最終用戶,當然還有討厭者:) 他們在 GitHub 上有 48k+ Stars,這使得他們足夠可信。 https://github.com/deepfakes/faceswap 明星 FaceSwap ⭐️ --- 6. [Amica](https://github.com/semperai/amica) - 讓您可以在瀏覽器中輕鬆地與 3D 角色聊天。 ---------------------------------------------------------------------- ![朋友](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2nvizcn717h3cteocft5.png) Amica 是一個開源接口,用於透過語音合成和語音辨識與 3D 角色進行互動式通訊。 您可以匯入 VRM 文件,調整聲音以適合角色,並產生包含情緒表達的回應文字。 他們使用 Three.js、OpenAI、Whisper、Bakllava 等進行視覺處理。您可以閱讀[Amica 的工作原理](https://docs.heyamica.com/overview/how-amica-works)及其所涉及的[核心概念](https://docs.heyamica.com/overview/core-concepts)。 您可以克隆該存儲庫並使用它來[開始](https://docs.heyamica.com/getting-started/installation)。 ``` npm i npm run dev ``` 您可以閱讀[文件](https://docs.heyamica.com/)並查看[演示](https://amica.arbius.ai/),這真是太棒了:D ![示範](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/92iv9y2auly6tvenee82.png) 您可以觀看這段簡短的影片,了解它的功能。 https://www.youtube.com/watch?v=hUxAEnFiXH8 Amica 使用 Tauri 建立桌面應用程式。 他們在 GitHub 上有 400+ Stars,而且看起來非常容易使用。 https://github.com/semperai/amica Star Amica ⭐️ --- 7. [Bark](https://github.com/suno-ai/bark) - 文字提示的生成音訊模型。 --------------------------------------------------------- ![吠](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pt8h5filcsk9pcxsx0ky.png) Bark 是 Suno 建立的基於轉換器的文本到音訊模型。 Bark 可以產生高度逼真的多語言語音以及其他音訊 - 包括音樂、背景噪音和簡單的音效。 該模型還可以產生非語言交流,如笑、嘆息和哭泣。哇! 它擁有 MIT 許可證,這意味著它現在可用於商業用途。 Bark 支援超過 100 種語言的揚聲器預設。您可以[在此處](https://suno-ai.notion.site/8b8e8749ed514b0cbf3f699013548683?v=bc67cff786b04b50b3ceb756fd05f68c)查看支援的語音預設庫。 根據文件,Bark 嘗試匹配給定預設的語氣、音高、情緒和韻律,但目前不支援自訂語音複製。該模型還嘗試保留音樂、環境噪音等。這超出了任何人的需要。 您可以這樣使用它。如果您想將其與 Transformers 庫一起使用,請閱讀[本文](https://github.com/suno-ai/bark?tab=readme-ov-file#-transformers-usage)。 ``` from bark import SAMPLE_RATE, generate_audio, preload_models from scipy.io.wavfile import write as write_wav from IPython.display import Audio # download and load all models preload_models() # generate audio from text text_prompt = """ Hello, my name is Suno. And, uh — and I like pizza. [laughs] But I also have other interests such as playing tic tac toe. """ audio_array = generate_audio(text_prompt) # save audio to disk write_wav("bark_generation.wav", SAMPLE_RATE, audio_array) # play text in notebook Audio(audio_array, rate=SAMPLE_RATE) ``` Bark 開箱即用支援各種語言,並自動根據輸入文字確定語言。當提示使用程式碼轉換文字時,Bark 將嘗試使用相應語言的本地口音。 您可以在[Google Colab](https://colab.research.google.com/drive/1eJfA2XUa-mXwdMy7DoYKVYHI1iTd9Vkt?usp=sharing) & [Replicate](https://replicate.com/suno-ai/bark)閱讀<a href="">文件</a>並查看演示。 您也可以在筆記本部分閱讀有關語音一致性增強和其他形式的[範例](https://github.com/suno-ai/bark/tree/main/notebooks)。 ![聲音](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zirh2dimya9yt8p0e7ry.png) 它們支援多種語言,如英語、印地語、德語、法語等。 他們在 GitHub 上擁有 30k+ Stars,並且經營超過 300,000 人的社區,這使他們成為值得選擇的選擇。 https://github.com/suno-ai/bark 星樹 ⭐️ --- 8. [GPTDiscord](https://github.com/Kav-K/GPTDiscord) - Discord 的一體化 GPT 介面。 --------------------------------------------------------------------------- ![概述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kknaijkgi2rr7b0kefo7.png) 我是 Discord 上多個社群的成員,具有出色用例的機器人可以改善整體最終用戶體驗。 這個機器人的功能與 ChatGPT 網路相當,甚至在某些事情上做得更好! 它們支援一切,從多模態圖像理解、程式碼解釋、高級資料分析、文件問答、與 Wolfram Alpha 的網路連接聊天和 Google 存取、AI 審核、使用 DALL-E 生成圖像等等! 您可以閱讀 GPTDiscord 的所有高效[功能](https://github.com/Kav-K/GPTDiscord?tab=readme-ov-file#features)。 您可以閱讀[安裝指南](https://github.com/Kav-K/GPTDiscord/blob/main/detailed_guides/INSTALLATION.md)。 您可以查看[螢幕截圖](https://github.com/Kav-K/GPTDiscord?tab=readme-ov-file#screenshots)並查看不同目的的[詳細指南](https://github.com/Kav-K/GPTDiscord/tree/main/detailed_guides)清單。 他們在 GitHub 上有大約 1.8k+ Stars,而且肯定在進步。 https://github.com/Kav-K/GPTDiscord 星 GPTDiscord ⭐️ --- 9. [Upscayl](https://github.com/upscayl/upscayl) - 開源 AI 影像擴大機。 --------------------------------------------------------------- ![高級](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2c1837rev5jb260ro2sd.png) 適用於 Linux、MacOS 和 Windows 的免費開源 AI Image Upscaler 採用 Linux 優先概念建構。 它可能與全端無關,但它對於升級圖像很有用。 ![高級](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9vyo1eqfz3hh0rg3lmkz.png) ![高級](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a4qq1wm3wey3vihn9al4.png) 透過最先進的人工智慧,Upscayl 可以幫助您將低解析度影像變成高解析度。清脆又鋒利! 您可以閱讀[安裝指南](https://github.com/upscayl/upscayl?tab=readme-ov-file#-installation),並查看 Upscayl 之前/之後的[比較](https://github.com/upscayl/upscayl/blob/main/COMPARISONS.MD)。 ![比較](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3f14g2vv58ljhayluh8l.png) 它在 GitHub 上有 23k+ Stars,並且基於 TypeScript 建置。 https://github.com/upscayl/upscayl 明星 Upscayl ⭐️ --- 10. [AppFlowy](https://github.com/AppFlowy-IO/AppFlowy) - Notion 的開源替代品。 ------------------------------------------------------------------------ ![應用程式串流](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dovisje3bh7ec1h9uqau.png) AppFlowy 是一個由人工智慧驅動的安全工作空間,類似於您在不失去資料控制的情況下實現更多目標的概念。 ![產品](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ul096wqbsxrs8shvwp6c.png) 他們還提供行動應用程式,這是一個優點。 您可以閱讀[文件](https://docs.appflowy.io/docs)並了解[安裝方法](https://docs.appflowy.io/docs/appflowy/install-appflowy/installation-methods)。 他們還支援[使用 Supabase 自託管 AppFlowy](https://docs.appflowy.io/docs/guides/appflowy) 。對於喜歡 Supabase 功能或使用 Supabase 作為其基礎設施的用戶來說,這是理想的選擇。 您還應該檢查[此內容](https://docs.appflowy.io/docs/appflowy/product/data-storage)以了解有關資料儲存、Markdown、捷徑、主題、涉及的人工智慧和插件的更多資訊。 AppFlowy 在 GitHub 上擁有超過 47,000 顆星,發布了 64 個以上版本。 https://github.com/AppFlowy-IO/AppFlowy 明星 AppFlowy ⭐️ --- 11. [Leon](https://github.com/leon-ai/leon) - 您的開源個人助理。 ------------------------------------------------------- ![萊昂](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mnv85osce6ps9xodf07t.png) Leon 是一個開源個人助理,可以駐留在您的伺服器上。 當你要求他做事時,他就會做事。 你可以跟他說話,他也可以跟你說話。你也可以給他發短信,他也可以傳簡訊給你。如果您願意,Leon 可以透過離線方式與您溝通,以保護您的隱私。這是萊昂目前可以做的[技能](https://github.com/leon-ai/leon/tree/develop/skills)清單。 你應該讀一下[萊昂背後的故事](https://blog.getleon.ai/the-story-behind-leon/)。您還可以觀看此演示以了解有關 Leon 的更多資訊。 https://www.youtube.com/watch?v=p7GRGiicO1c ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/70mddmgadcbfwzugd1bl.png) 這是Leon的高層架構模式。 ![建築學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a6b9vgj3fagera0bsyur.png) 這是開始使用 npm 指令的方法。 ``` # install leon global cli npm install --global @leon-ai/cli # install leon leon create birth ``` 您可以閱讀[文件](https://docs.getleon.ai/)。 它在 GitHub 上擁有超過 14k 顆星,並且還在不斷增長。 https://github.com/leon-ai/leon 明星萊昂 ⭐️ --- 12. [n8n](https://github.com/n8n-io/n8n) - 工作流程自動化工具。 ----------------------------------------------------- ![n8n](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4pqsc84nhgj0b9dhfaxo.png) n8n 是一個可擴展的工作流程自動化工具。透過公平程式碼分發模型,n8n 將始終擁有可見的原始程式碼,可用於自託管,並允許您加入自訂函數、邏輯和應用程式。 ![n8n](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxnp57kw5szbpj6mfs1p.png) n8n 基於節點的方法使其具有高度通用性,使您能夠將任何事物連接到任何事物。 有[400 多個集成選項](https://n8n.io/integrations),這幾乎是瘋狂的! 您可以看到所有[安裝](https://docs.n8n.io/choose-n8n/)選項,包括 Docker、npm 和自架。 開始使用以下命令。 ``` npx n8n ``` 此命令將下載啟動 n8n 所需的所有內容。然後,您可以透過開啟`http://localhost:5678`來存取 n8n 並開始建置工作流程。 在 YouTube 上觀看此[快速入門影片](https://www.youtube.com/watch?v=1MwSoB0gnM4)! https://www.youtube.com/watch?v=1MwSoB0gnM4 您可以閱讀[文件](https://docs.n8n.io/)並閱讀本[指南](https://docs.n8n.io/try-it-out/),以便根據您的需求快速開始。 他們還提供初學者和中級[課程,](https://docs.n8n.io/courses/)以便輕鬆學習。 他們在 GitHub 上有 39k+ Stars,並提供兩個包供整體使用。 https://github.com/n8n-io/n8n 明星 n8n ⭐️ --- 13. [Quivr](https://github.com/QuivrHQ/quivr) - 你的 GenAI 第二腦。 ------------------------------------------------------------- ![奎弗爾](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hl12fl88mdjmfkfath1t.png) Quivr,您的第二個大腦,利用 GenerativeAI 的力量成為您的私人助理!可以將其視為黑曜石,但增強了人工智慧功能。 ![統計資料](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5a27c2ubbmri0b2xlh1l.png) 您可以閱讀[安裝指南](https://github.com/QuivrHQ/quivr?tab=readme-ov-file#getting-started-)。 您可以閱讀[文件](https://docs.quivr.app/home/intro)並觀看[示範影片](https://github.com/QuivrHQ/quivr?tab=readme-ov-file#demo-highlights-)。 他們可以提供更好的免費套餐,但這足以在您端進行測試。 它在 GitHub 上擁有超過 30k 顆星,發布了 220 多個版本,這意味著它們正在不斷改進。 https://github.com/QuivrHQ/quivr Star Quivr ⭐️ --- 14. [meilisearch](https://github.com/meilisearch/meilisearch) - 適合您的應用程式、網站和工作流程的搜尋 API。 ---------------------------------------------------------------------------------------- ![搜尋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s1rm66br9fbsa76n2e8i.png) Meilisearch 可協助您快速打造令人愉悅的搜尋體驗,提供開箱即用的功能來加快您的工作流程。 您一定看過可以使用`Ctrl + k`搜尋文件的軟體網站,例如 GitHub 或 Appwrite。那麼,meilisearch 可以幫助您實現相同的功能。 與 Algolia、Typesense 和 Elasticsearch 相比,這是唯一基於 Rust 建構的。您可以閱讀有關可用替代選項的[比較](https://www.meilisearch.com/docs/learn/what_is_meilisearch/comparison_to_alternatives):) Meilisearch 不應該是您的主要資料儲存。它是一個搜尋引擎,而不是一個資料庫。 Meilisearch 應僅包含您希望使用者搜尋的資料。如果您必須加入與搜尋無關的資料,請務必使這些字段不可搜尋,以提高相關性並縮短響應時間。 無論您是在開發網站還是應用程式,Meilisearch 都能提供直覺的即輸入即搜尋體驗,回應時間低於 50 毫秒。 他們提供[SDK 和庫,](https://www.meilisearch.com/docs/learn/what_is_meilisearch/sdks?utm_campaign=oss&utm_source=github&utm_medium=meilisearch&utm_content=sdks-link)用於 Meilsearch 和您喜歡的語言或框架之間的無縫整合。相信我,選擇的數量是瘋狂的。 他們還提供了一個[抓取工具](https://github.com/meilisearch/docs-scraper)來自動讀取文件內容並將其儲存到Meilisearch。 他們展示了許多[有用的功能](https://www.meilisearch.com/docs/learn/what_is_meilisearch/overview#features),例如即使查詢包含拼寫錯誤和拼寫錯誤(他們將其稱為`typo tolerance` ,您也可以獲得相關匹配。 有很多可用的選項,但讓我們看看如何使用 React 來做到這一點。 開始使用以下命令。 ``` yarn add react-instantsearch @meilisearch/instant-meilisearch # or npm install react-instantsearch @meilisearch/instant-meilisearch # or pnpm add react-instantsearch @meilisearch/instant-meilisearch ``` 您可以這樣使用它。 ``` import React from 'react'; import { InstantSearch, SearchBox, Hits, Highlight } from 'react-instantsearch'; import { instantMeiliSearch } from '@meilisearch/instant-meilisearch'; const { searchClient } = instantMeiliSearch( 'https://ms-adf78ae33284-106.lon.meilisearch.io', 'a63da4928426f12639e19d62886f621130f3fa9ff3c7534c5d179f0f51c4f303' ); const App = () => ( <InstantSearch indexName="steam-video-games" searchClient={searchClient} > <SearchBox /> <Hits hitComponent={Hit} /> </InstantSearch> ); const Hit = ({ hit }) => <Highlight attribute="name" hit={hit} />; export default App ``` 您可以查看此[codesandbox](https://codesandbox.io/p/sandbox/eager-dust-f98w2w)以取得詳細的範例以開始使用。 正如我所說,他們在幕後提供了很多東西。例如,您可以使用這些。 ``` npm install @meilisearch/autocomplete-client npm install @meilisearch/instant-meilisearch npm install meilisearch-docsearch ``` `meilisearch docsearch`的靈感來自 Algolia 搜尋文件元件。另外,非常詳細的文件以及每個 sdk 的範例和選項使它們成為人們的最愛。 您可以閱讀[文件](https://www.meilisearch.com/docs)並觀看[現場演示](https://where2watch.meilisearch.com/?utm_campaign=oss&utm_source=github&utm_medium=meilisearch&utm_content=demo-link)。 ![社區統計](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cxou5qe4p0va0h8r52ti.png) 他們在 GitHub 上有超過 42k 顆星,並且`v1.7`版本有 180 多個版本。 https://github.com/meilisearch/meilisearch 星 meilisearch ⭐️ --- 15.[收件匣清除](https://github.com/elie222/inbox-zero)- 幾分鐘內清理您的收件匣。 --------------------------------------------------------------- ![收件匣為零](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jz1krkg9btykpfoiuukd.png) 收件匣歸零是一款開源電子郵件應用程式,其目標是透過 AI 協助幫助您快速實現收件匣歸零。 它們得到了谷歌的批准,因此這是關注隱私的一個很好的部分。 ![經谷歌批准](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9fidgtozaj9y4feo4bbq.png) 它們使用 Postgres 作為資料庫,並基於 TypeScript 建置。 它們有一些瘋狂的功能,例如: > 您的電子郵件人工智慧助理 1. 人工智慧代理將讓您根據您提供的規則自動回覆、轉發或存檔電子郵件。 2. 他們的人工智慧計畫可以幫助你點擊接受或拒絕。一旦您確信人工智慧可以獨立工作,就可以開啟完全自動化。 3. 您可以用簡單的英語進行指導。就像與助手交談或向 ChatGPT 發送提示一樣簡單。 > 您可以自動封鎖冷電子郵件 您可以告訴「收件匣零」什麼對您來說構成冷郵件。它將根據您的指示阻止它們。 > 分析 了解收件匣是處理它的第一步。了解您的收件匣裡裝滿了什麼。它們還為您提供了立即採取行動的方法。 您可以閱讀核心[功能](https://github.com/elie222/inbox-zero?tab=readme-ov-file#key-features)並觀看[演示影片](https://github.com/elie222/inbox-zero?tab=readme-ov-file#demo-video)。您還可以查看他們的[看板](https://github.com/users/elie222/projects/1/views/1)以了解計劃內容。 他們在 GitHub 上擁有超過 1,500 個 Star,並且絕對值得更多。 https://github.com/elie222/inbox-zero 星收件匣零 ⭐️ --- 16. [Lively](https://github.com/rocksdanister/lively) - 允許使用者設定動畫桌面桌布和螢幕保護程式。 ----------------------------------------------------------------------------- ![活潑](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60tld1a857herh12r5ci.png) 這只是為了好玩,我們可以使用程式碼學到很多關於它是如何完成的。 你可以看看這個[影片](https://www.pexels.com/video/blue-texture-abstract-leaves-7710243/),看看它看起來有多瘋狂。 ![風俗](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kb2ll571uc2jd2xrpmph.png) 他們提供[三種類型的壁紙,](https://github.com/rocksdanister/lively?tab=readme-ov-file#types-of-wallpapers)包括影片/GIF、網頁和應用程式/遊戲。 它基於 C# 和 live 支援的一些很酷的功能建置: 1. Lively 可以透過終端機的[命令列參數](https://github.com/rocksdanister/lively/wiki/Command-Line-Controls)進行控制。您可以將其與其他語言(例如 Python 或腳本軟體 AutoHotKey)整合。 2. 一組強大的[API](https://github.com/rocksdanister/lively/wiki/API) ,供開發人員建立互動式壁紙。取得硬體讀數、音訊圖表、音樂資訊等。 3. 當電腦上執行全螢幕應用程式/遊戲時(~0% CPU、GPU 使用率),桌布播放會暫停。 4. 您還可以利用[機器學習推理](https://github.com/rocksdanister/lively/wiki/Machine-Learning)來建立動態壁紙。您可以預測任何 2D 影像與相機的距離並產生類似 3D 的視差效果。酷:D 我見過很多人使用它,其中許多人甚至不知道它是開源的。 您可以使用[安裝程式](https://github.com/rocksdanister/lively/releases/download/v2.0.7.4/lively_setup_x86_full_v2074.exe)或透過[Microsoft Store](https://www.microsoft.com/store/productId/9NTM2QC6QWS7?ocid=pdpshare)下載它。 它是 2023 年 Microsoft Store 的獲勝者。 它在 GitHub 上擁有 13k+ Stars,有 60 個版本。 https://github.com/rocksdanister/lively 明星活潑 ⭐️ --- 17. [Netron](https://github.com/lutzroeder/netron) - 神經網路、深度學習和機器學習模型的視覺化工具。 ---------------------------------------------------------------------------- ![內創標誌](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uyvww60nqm4jrah526w2.png) Netron 是神經網路、深度學習和機器學習模型的檢視器。 Netron 支援 ONNX、TensorFlow Lite、Core ML、Keras、Caffe、Darknet、MXNet、PaddlePaddle、ncnn、MNN 和 TensorFlow.js。 Netron 對 PyTorch、TorchScript、TensorFlow、OpenVINO、RKNN、MediaPipe、ML.NET 和 scikit-learn 提供實驗性支援。 您可以閱讀有關[安裝說明](https://github.com/lutzroeder/netron?tab=readme-ov-file#install)。 您可以存取該[網站](https://netron.app/)並打開這些[範例模型文件](https://github.com/lutzroeder/netron?tab=readme-ov-file#models)以使用它來打開。例如,您可以看到這個[演示](https://netron.app/?url=https://github.com/onnx/models/raw/main/validated/vision/classification/squeezenet/model/squeezenet1.0-3.onnx)。 ![模型](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z1h4si8oue41x1i7dss5.png) 他們在 GitHub 上有 25k+ Stars,並且是基於 JavaScript 建構的。它們在`v7.5`上只有三個版本,考慮到我只使用了語義版本,這對我來說似乎很困惑。我們都同意這個用例非常出色。 https://github.com/lutzroeder/netron 明星 Netron ⭐️ --- 18. [Cursor](https://github.com/getcursor/cursor) - 以 VSCode 為基礎的人工智慧程式碼編輯器。 ---------------------------------------------------------------------------- ![游標](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k7em09r6owbz35zh8tt0.png) Cursor 是一款專為與 AI 結對程式設計而設計的程式碼編輯器。遊標適用於 Windows、Mac 和 Linux。 Cursor 不僅僅是 Visual Studio Code (VSC) 擴充功能。這是它自己的應用程式。但別擔心!這是VSC前叉。這意味著它擁有 VSC 所擁有的一切,但在此基礎上也建立了更多人工智慧功能。 https://github.com/anysphere/primpt 他們之前開源了[基於 Codemirror 的編輯器](https://github.com/getcursor/old)。 基於 VSCodium 的 Cursor 版本不是開源的,只有它們的[提示庫](https://github.com/anysphere/priompt)是開源的。 選項數量龐大,您可以查看[功能列表](https://docs.cursor.sh/features/chat),例如選擇用於聊天的 AI 模型、程式碼庫索引和自動終端偵錯。聽起來很酷,對吧:D 您應該檢查的一些功能是: - 允許您透過編輯程式碼庫的「偽程式碼」版本來進行編碼。 - 一旦錯誤出現在您的終端機中,就會自動修復錯誤。 - 要求 AI 更改程式碼區塊,查看編輯的內聯差異。 您也可以閱讀他們官方網站的[變更日誌](https://changelog.cursor.sh/?)。 您可以閱讀有關如何從[VSCode 遷移到 Cursor 的](https://docs.cursor.sh/get-started/moving-from-vsc-to-cursor)資訊。 他們也有定價模型,但免費套餐足以讓您進行測試! 他們在 GitHub 上擁有超過 19k+ 的 Star,並將繼續成長。正如我所說,這不是開源的,但將來可能會改變。 https://github.com/getcursor/cursor 星形遊標 ⭐️ --- 19. [VSCode 除錯視覺化工具](https://github.com/hediet/vscode-debug-visualizer)- VS Code 的擴展,可在偵錯期間可視化資料。 ------------------------------------------------------------------------------------------------- ![VSCode 除錯視覺化工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7hzgtqb6396zx73d3y62.png) 這個專案相當令人印象深刻。它不僅有助於高效除錯,還有助於透過視覺化學習基本概念,從長遠來看,這是無價的。 這是一個 VS Code 擴展,用於在偵錯時可視化資料結構。與 VS Code 的監視視圖類似,但具有豐富的監視值視覺化效果。 他們支援許多語言,如 Dart/Flutter、JS/TS、Go、Python、C#、Java、C++、Ruby、Rust 和 Swift,儘管它很基礎,所以這是一個優點。 其他語言和除錯器也可能有效。對於有基本支援的語言,只能視覺化 JSON 字串。您需要實作邏輯來為您的資料結建置立此 JSON。完全支援的語言提供資料提取器,可將一些眾所周知的資料結構轉換為 JSON。 安裝擴充功能後,您可以使用命令`Debug Visualizer: New View`開啟新的視覺化工具視圖。 您可以[在 market 上](https://marketplace.visualstudio.com/items?itemName=hediet.debug-visualizer)查看所有可用的[演示](https://github.com/hediet/vscode-debug-visualizer/blob/master/extension/README.md#selected-demos)並查看擴展。 您還可以查看他們的[視覺化遊樂場](https://hediet.github.io/visualization/?darkTheme=1),其中包含眾多選項。 他們在 GitHub 上擁有超過 7800 顆星,而且還在不斷增長。 https://github.com/hediet/vscode-debug-visualizer 明星 VSCode 除錯視覺化工具 ⭐️ --- 20. [OpenDevin](https://github.com/OpenDevin/OpenDevin) - 更少的程式碼,更多的內容。 ----------------------------------------------------------------------- ![奧彭文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4on63bb02g4x4ny8gtcn.png) ![奧彭文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0yepod2rye2jk5r12dt.png) 這是一個開源專案,旨在複製 Devin,一名自主人工智慧軟體工程師,能夠執行複雜的工程任務並在軟體開發專案上與用戶積極協作。該計畫致力於透過開源社群的力量複製、增強和創新 Devin。 只是想讓你知道,這是在德文被介紹之前。 您可以閱讀帶有要求的[安裝說明](https://github.com/OpenDevin/OpenDevin?tab=readme-ov-file#installation)。 他們使用 LiteLLM,因此您可以使用任何基礎模型來執行 OpenDevin,包括 OpenAI、Claude 和 Gemini。 如果您想為 OpenDevin 做出貢獻,您可以查看 [演示](https://github.com/OpenDevin/OpenDevin/blob/main/README.md#opendevin-code-less-make-more)和[貢獻指南](https://github.com/OpenDevin/OpenDevin/blob/main/CONTRIBUTING.md)。 它在 GitHub 上擁有超過 10,700 個 Star,並且正在快速成長。 https://github.com/OpenDevin/OpenDevin 明星 OpenDevin ⭐️ --- 21.[即時語音克隆](https://github.com/CorentinJ/Real-Time-Voice-Cloning)-5秒克隆語音,即時產生任意語音。 ---------------------------------------------------------------------------------- ![即時語音克隆](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ftnuelce5cwng0nunp2h.png) 該專案是透過即時工作的聲碼器實現從說話者驗證到多說話者文字到語音合成 (SV2TTS) 的遷移學習。 SV2TTS是一個分為三個階段的深度學習架構。 在第一階段,人們從幾秒鐘的音訊中建立聲音的數位表示。 在第二和第三階段,該表示被用作參考來產生給定任意文字的語音。 您可以閱讀[如何設定](https://github.com/CorentinJ/Real-Time-Voice-Cloning?tab=readme-ov-file#setup)專案,其中包括安裝要求、下載預訓練模型、測試配置、下載資料集和啟動工具箱。 觀看下面所示的影片示範! https://www.youtube.com/watch?v=-O\_hYhToKoA 我一直喜歡開源專案的最好的部分是,他們甚至非常清楚地提到了替代方案,並且像往常一樣,他們推薦了一些[專案](https://github.com/CorentinJ/Real-Time-Voice-Cloning?tab=readme-ov-file#heads-up),這些專案將為您克隆的聲音提供更好的保真度及其表現力。 他們在 GitHub 上擁有 50k+ Stars,並且僅基於 Python 建置。到目前為止使用起來還是非常可信的。 https://github.com/CorentinJ/Real-Time-Voice-Cloning Star 即時語音克隆 ⭐️ --- 請在評論中告訴我您在此列表中發現了哪些有用的人工智慧工具:D 人工智慧正在改變世界,最好讓人工智慧成為你的朋友,而不是簡單地忽略它。 使用這些工具來提高工作效率並抓住機會創造非凡的東西。 祝你有美好的一天!直到下一次。 在 GitHub 和[Twitter](https://twitter.com/Anmol_Codes)上關注我。 https://github.com/Anmol-Baranwal 關注 Taipy 以了解更多此類內容。 https://dev.to/taipy --- 原文出處:https://dev.to/taipy/21-ai-tools-that-are-changing-the-world-1o54

從頭開始寫簡單的程式語言 - 第 1 部分

如果您是開發人員,您就使用過程式語言。它們是讓電腦做你想做的事的好方法。也許您甚至已經深入研究過彙編或機器碼程式設計。許多人再也不想回來。但有些人想知道,我怎麼能透過做更多的低階程式來更折磨自己呢?我想更多地了解程式語言是如何製作的!開個玩笑,寫一門新語言並不像聽起來那麼糟糕,所以如果你有一點好奇心,我建議你留下來看看它是關於什麼的。 這篇文章的目的是簡單地介紹如何建立程式語言,以及如何建立自己的特殊語言。甚至可以用自己的名字命名。誰知道。 我還敢打賭,這似乎是一項令人難以置信的艱鉅任務。別擔心,因為我已經考慮過這一點。我盡力相對簡單地解釋了一切,沒有講*太多*離題的話。在這篇文章結束時,您將能夠建立自己的程式語言(將有幾個部分),但還有更多。了解幕後發生的事情會讓你更好地進行除錯。您將更能理解新的程式語言以及為何它們做出這樣的決定。如果我之前沒有提到的話,你可以擁有一種以你自己的名字命名的程式語言。而且,這真的很有趣。至少對我來說。 編譯器和解釋器 ------- 程式語言通常是高階的。也就是說,你看的不是0和1,也不是暫存器和組合程式碼。但是,您的電腦只能辨識 0 和 1,因此它需要一種方法來從您輕鬆讀取的內容轉變為機器可以輕鬆讀取的內容。該翻譯可以透過編譯或解釋來完成。 編譯是將原始語言的整個原始檔轉換為目標語言的過程。出於我們的目的,我們將考慮從全新的、最先進的語言一直編譯到可執行的機器碼。 ![簡單編譯圖](https://thepracticaldev.s3.amazonaws.com/i/c5difsv2s2rvk1iwzcih.png) 我的目標是讓「魔法」消失 解釋是或多或少直接執行原始檔中的程式碼的過程。我會讓你覺得這很神奇。 那麼,如何從易於閱讀的原始語言變成難以理解的目標語言呢? 編譯器的階段 ------ 編譯器可以透過多種方式分為多個階段,但有一種方法是最常見的。當你第一次看到它時,它的意義不大,但它是這樣的: ![編譯器的虛假階段](https://thepracticaldev.s3.amazonaws.com/i/cq1uo0x1gp7k73jldp7o.png) 哎呀,我選錯了圖,但這樣就可以了。基本上,您獲取原始文件,將其設置為計算機想要的格式(刪除空格之類的內容),將其更改為計算機可以很好地移動的格式,然後從中生成程式碼。還有更多。那是下次,或者如果你的好奇心快要殺死你的話,也可以供你自己研究。 詞法分析 ---- ### 又名“讓原始碼變得漂亮” 考慮以下完全虛構的語言,它基本上只是一個帶有分號的計算器: ``` // source.ect 3 + 3.2; 5.0 / 1.9; 6 * 2; ``` 計算機不需要所有這些。空間只適合我們狹隘的頭腦。還有新線?沒有人需要那些。電腦將您看到的程式碼轉換為可以使用的標記流,而不是原始檔案。基本上,它知道`3`是整數, `3.2`是浮點數, `+`是對這兩個值進行運算的東西。這就是計算機*真正*需要完成的全部工作。**詞法分析器**的工作是提供這些標記而不是原始程式。 它的實現方式非常簡單:給詞法分析器(詞法分析器的一種聽起來不那麼自命不凡的說法)一些期望的東西,然後告訴它當它看到這些東西時要做什麼。這些稱為*規則*。這是一個例子: ``` int cout << "I see an integer!" << endl; ``` 當 int 通過詞法分析器並執行此規則時,您將看到一個非常明顯的“我看到一個整數!”感嘆。這不是我們使用詞法分析器的方式,但看到程式碼執行是任意的很有用:沒有規則要求您必須建立某個物件並傳回它,它只是常規的舊程式碼。甚至可以用大括號括起來來使用多條線。 順便說一句,我們將使用稱為[FLEX 的](https://github.com/westes/flex)東西來進行詞法分析。它使事情變得非常簡單,但是沒有什麼可以阻止您自己編寫一個程式來執行此操作。 為了了解我們如何使用 flex,請看這個例子: ``` // scanner.lex /* Definitions */ %{ #include <iostream> using namespace std; extern "C" int yylex(); %} /* Rules next */ %% [0-9]+.[0-9]+ cout << "FLOAT: (" << yytext << ")" << endl; [0-9]+ cout << "INT: (" << yytext << ")" << endl; "+" cout << "PLUS" << endl; "-" cout << "MINUS" << endl; "*" cout << "TIMES" << endl; "/" cout << "DIVIDED BY" << endl; ";" cout << "SEMICOLON" << endl; [\t\r\n\f] ; /* ignore whitespace */ %% /* Code */ int main() { yylex(); } ``` 這引入了一些新概念,讓我們回顧一下它們: `%%`用於分隔 .lex 檔案的各個部分。第一部分是聲明 - 基本上是使詞法分析器更具可讀性的變數。這也是您導入的位置,由`%{`和`%}`包圍。 第二部分是規則,我們之前已經看過。這些基本上是一個大的`if` `else if`塊。它將執行*最長的匹配*行。因此,即使您更改 float 和 int 的順序,float 仍然會匹配,因為匹配`3.2`的 3 個字元比`3`的 1 個字元多。請注意,如果這些規則均不匹配,則會採用預設規則,只需將字元列印到標準輸出即可。然後,您可以使用`yytext`來引用它看到的與該規則相符的內容。 第三部分是程式碼,它只是在執行時執行的 C 或 C++ 原始碼。 `yylex();`是執行詞法分析器的函數呼叫。您也可以讓它從檔案中讀取輸入,但預設情況下它從標準輸入中讀取。 假設您將這兩個檔案建立為`source.ect`和`scanner.lex` 。我們可以使用`flex`命令建立一個 C++ 程式(假設您已經安裝了`flex` ),然後編譯它並輸入我們的原始程式碼以達到我們很棒的列印語句。讓我們將其付諸行動吧! ``` evan:ectlang/ $ flex scanner.lex evan:ectlang/ $ g++ lex.yy.c -lfl evan:ectlang/ $ ./a.out < source.ect INT: (3) PLUS FLOAT: (3.2) SEMICOLON FLOAT: (5.0) DIVIDED BY FLOAT: (1.9) SEMICOLON INT: (6) TIMES INT: (2) SEMICOLON evan:ectlang/ $ ``` 嘿,酷!您只需編寫將輸入與規則相符的 C++ 程式碼,以便執行某些操作。 現在,編譯器如何使用它?一般來說,每個規則都會返回一些東西,而不是打印一些東西——一個令牌!這些標記可以在編譯器的下一部分中定義... 語法分析器 ----- ### 又名“使漂亮的源程式碼可用” 是時候玩得開心了!一旦我們到達這裡,我們就開始定義程式的結構。解析器只是獲得一個標記流,它必須匹配該流中的元素,以使原始程式碼具有可用的結構。為了做到這一點,它使用了[語法](https://en.wikipedia.org/wiki/Formal_grammar),你可能在理論課上看到或聽到你奇怪的朋友閒聊的東西。它們非常強大,並且有很多東西需要了解,但我只會提供您需要了解的關於我們有點愚蠢的解析器的資訊。 基本上,語法將非終結符與終結符和非終結符的某種組合相匹配。終端是樹的葉子;非終端有孩子。如果這沒有意義,請不要擔心,程式碼可能會更容易理解。 我們將使用一個名為[Bison 的](https://www.gnu.org/software/bison/)解析器產生器。這次,為了解釋目的,我將把文件分成幾個部分。首先,聲明: ``` // parser.y %{ #include <iostream> using namespace std; extern "C" void yyerror(char *s); extern "C" int yyparse(); %} %union{ int intVal; float floatVal; } %start program %token <intVal> INTEGER_LITERAL %token <floatVal> FLOAT_LITERAL %token SEMI %type <floatVal> exp %type <floatVal> statement %left PLUS MINUS %left MULT DIV ``` 第一部分應該看起來很熟悉:我們正在導入我們想要使用的東西。之後就變得有點棘手了。 聯合是「真正的」C++ 類型到我們將在整個程式中呼叫它的類型的映射。因此,當我們看到`intVal`時,您可以將頭腦中的值替換為`int` ,而當我們看到`floatVal`時,您可以將頭腦中的值替換為`float` 。稍後你就會明白為什麼。 接下來我們來看看符號。您可以在腦海中將它們分為終結符和非終結符,就像我們之前討論的語法一樣。大寫字母表示終端,因此它們不會繼續擴展。小寫意味著非終結符,因此它們繼續擴展。這只是慣例。 每個聲明(以`%`開頭)聲明一些符號。首先,我們看到我們從一個非終端`program`開始。然後,我們定義一些標記。 `<>`括號定義回傳類型:因此`INTEGER_LITERAL`終端機回傳`intVal` 。 `SEMI`終端不會回傳任何內容。使用`type`可以對非終結符完成類似的操作,如將`exp`定義為傳回`floatVal`的非終結符時所見。 最後我們取得了優先權。我們知道 PEMDAS,或者您可能已經學過的任何其他縮寫詞,它告訴您一些簡單的優先規則:乘法在加法之前,等等。現在,我們以一種奇怪的方式在這裡聲明這一點。首先,清單中的位置越低意味著優先順序越高。其次,您可能想知道`left`是什麼意思。這就是關聯性:差不多,如果我們有`a op b op c` , `a`和`b`會在一起,還是`b`和`c`會在一起?我們的大多數運算子都執行前者,即`a`和`b`首先結合在一起:這稱為左結合性。某些運算子(例如求冪)會執行相反的操作: `a^b^c`期望您先提高`b^c`然後再提高`a^(b^c)` 。不過,我們不會處理這個問題。如果您想了解更多詳細訊息,請查看 Bison 頁面。 好吧,我可能已經厭倦了聲明,這是語法規則: ``` // parser.y %% program: /* empty */ | program statement { cout << "Result: " << $2 << endl; } ; statement: exp SEMI exp: INTEGER_LITERAL { $$ = $1; } | FLOAT_LITERAL { $$ = $1; } | exp PLUS exp { $$ = $1 + $3; } | exp MINUS exp { $$ = $1 - $3; } | exp MULT exp { $$ = $1 * $3; } | exp DIV exp { $$ = $1 / $3; } ; ``` 這就是我們之前講的文法。如果您不熟悉語法,這非常簡單:左側可以變成右側的任何內容,並用`|`分隔。 (邏輯`or` )。如果它可以走多條路徑,那就是不行的,我們稱之為*歧義語法*。由於我們的優先聲明,這並不含糊 - 如果我們更改它,使 plus 不再保持關聯,而是聲明為像`SEMI`這樣的`token` ,我們會看到發生移位/歸約衝突。想知道更多?看看Bison是如何運作的,提示,它使用LR解析演算法。 好的,所以`exp`可以是以下情況之一: `INTEGER_LITERAL` 、 `FLOAT_LITERAL`等。請注意,它也是遞歸的,因此`exp`可以變成兩個`exp` 。這允許我們使用複雜的表達式,例如`1 + 2 / 3 * 5` 。請記住,每個`exp`都會傳回一個 float 類型。 括號內的內容與我們在詞法分析器中看到的相同:任意 C++ 程式碼,但帶有更奇怪的語法糖。在這種情況下,我們有一些以`$`開頭的特殊變數。變數`$$`基本上就是回傳的內容。 `$1`是第一個參數傳回的內容, `$2`第二個參數傳回的內容,等等。我所說的「參數」是指語法規則的一部分:因此規則`exp PLUS exp`有參數 1 `exp` 、參數 2 `PLUS`和參數 3 `exp` 。因此,在程式碼執行中,我們將第一個表達式的結果加到第三個表達式中。 最後,一旦它回到`program`非終端,它將列印語句的結果。在這種情況下,程式是一堆語句,其中語句是一個表達式,後面跟著一個分號。 現在我們來編寫程式碼部分。這是當我們通過解析器時實際執行的內容: ``` // parser.y %% int main(int argc, char **argv) { if (argc < 2) { cout << "Provide a filename to parse!" << endl; exit(1); } FILE *sourceFile = fopen(argv[1], "r"); if (!sourceFile) { cout << "Could not open source file " << argv[1] << endl; exit(1); } // Sets input for flex to the file instead of standard in yyin = sourceFile; // Now let's parse it! yyparse(); } // Called on error with message s void yyerror(char *s) { cerr << s << endl; } ``` 好吧,這開始變得有趣了。我們的主函數現在從第一個參數提供的檔案而不是標準輸入中讀取,並且我們加入了一些錯誤程式碼。這是非常不言自明的,並且註釋很好地解釋了正在發生的事情,所以我將把它作為練習留給讀者來弄清楚這一點。您需要知道的是現在我們回到詞法分析器以向解析器提供標記!這是我們的新詞法分析器: ``` // scanner.lex %{ extern "C" int yylex(); #include "parser.tab.c" // Defines the tokens %} %% [0-9]+ { yylval.intVal = atoi(yytext); return INTEGER_LITERAL; } [0-9]+.[0-9]+ { yylval.floatVal = atof(yytext); return FLOAT_LITERAL; } "+" { return PLUS; } "-" { return MINUS; } "*" { return MULT; } "/" { return DIV; } ";" { return SEMI; } [ \t\r\n\f] ; /* ignore whitespace */ ``` 嘿嘿,現在確實變小了!我們看到的是,我們回傳的是終端符號,而不是列印。其中一些,例如整數和浮點數,我們首先在繼續之前設定值( `yylval`是終端符號的回傳值)。除此之外,它只是為解析器提供了一個終端標記流以供其自行決定使用。 酷,那麼讓我們執行吧! ``` evan:ectlang/ $ bison parser.y evan:ectlang/ $ flex scanner.lex evan:ectlang/ $ g++ lex.yy.c -lfl evan:ectlang/ $ ./a.out source.ect Result: 6.2 Result: 2.63158 Result: 12 ``` 我們開始了 - 我們的解析器列印出正確的值!但這並不是真正的編譯器,它只是執行 C++ 程式碼來執行我們想要的內容。為了製作編譯器,我們希望將其轉換為機器碼。為此,我們需要加入一點... 直到下次... ------- 我現在意識到這篇文章會比我想像的要長很多,所以我想我應該在這裡結束這篇文章。我們基本上有一個可用的詞法分析器和解析器,所以這是一個很好的停止點。 如果您對最終產品感到好奇,我已將原始程式碼放在[我的 Github](https://github.com/evantypanski/ectlang)上。隨著更多帖子的發布,該存儲庫將出現更多活動。 有了我們的詞法分析器和解析器,我們現在可以產生程式碼的中間表示,該中間表示最終可以轉換為真實的機器碼,我將向您展示具體的操作方法。 [第 2 部分來了!](https://dev.to/evantypanski/writing-a-simple-programming-language-from-scratch-part-2-2522) ### 其他資源 如果您想了解有關此處介紹的任何內容的更多訊息,我已經連結了一些內容以供您開始使用。我已經講了很多,所以這是我向您展示如何深入研究這些主題的機會。 - Flex 程式碼庫: <https://github.com/westes/flex> - 我們使用的詞法分析工具。 - Bison 文件: <https://www.gnu.org/software/bison/> - 我們使用的解析器產生器。這裡有很棒的文件。 - LALR 解析: <https://web.cs.dal.ca/~sjackson/lalr1.html> - 關於 LALR(1) 解析器(如 Bison 產生的解析器!)如何運作的精心解釋。 - 解決解析衝突: <http://www.cs.ecu.edu/karl/5220/spr16/Notes/Bottom-up/conflict.html> - 如何解決shift/reduce或reduce/reduce衝突,就像我們之前看到的那樣。 - Chomsky 層次結構: [https://en.wikipedia.org/wiki/Chomsky\_hierarchy](https://en.wikipedia.org/wiki/Chomsky_hierarchy) - 對此沒有詳細介紹,但我們使用了上下文無關語法,以便 Bison 可以編譯它。如果您需要上下文敏感性,那是為了後面的階段。 - 符號表: [https://www.tutorialspoint.com/compiler\_design/compiler\_design\_symbol\_table.htm](https://www.tutorialspoint.com/compiler_design/compiler_design_symbol_table.htm) - 使用符號表,編譯器如何處理變數。 哦,順便說一句,如果您不喜歡我的編譯器階段,這裡有一個實際的圖表。我仍然保留了符號表和錯誤處理程序。另請注意,許多圖表與此不同,但這最好地說明了我們所關心的內容。 ![編譯器的實際階段](https://thepracticaldev.s3.amazonaws.com/i/4bgv9blwleizrmcfw2fq.png) --- 原文出處:https://dev.to/evantypanski/writing-a-simple-programming-language-from-scratch-part-1-54a2

使用這些 React 函式庫和雲端後端來建立全端應用程式。

今天,我們將學習如何使用 Wing 作為後端建立全端應用程式。 ![反應 + 維特 + 翅膀](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vb7jf7dk9b08x042p0vl.png) 我們將使用 React 和 Vite 作為前端。 我知道還有其他框架,如 Vue、Angular 和 Next,但 React 仍然是最常見的,並且迄今為止有大量值得信賴的新創公司使用它。 如果您不知道, [React](https://github.com/facebook/react)是 Facebook 建立的開源程式庫,用於建立 Web 和本機使用者介面。正如您從儲存庫中看到的,它被超過 2040 萬開發人員使用。所以,這是值得的。 讓我們看看如何使用 Wing 作為後端。 ![豎起大拇指](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pskz2tyzodt4wnxbqa8y.gif) --- [Wing](https://git.new/wing-repo) - 一種雲端程式語言。 --------------------------------------------- ![翅膀](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n97bowkrexjk46n94bcc.png) Winglang 是一種專為雲端(又稱「面向雲端」)設計的新型開源程式語言。它允許您在雲端中建立應用程式,並且具有相當簡單的語法。 Wing 程式可以使用功能齊全的模擬器在本地執行(是的,不需要網路),也可以部署到任何雲端供應商。 ![機翼基礎設施](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eun3zd1gkp870rj57eeu.png) Wing 需要 Node `v20 or higher` 。 建立一個父目錄(我們使用的`shared-counter` )並使用 Vite 使用新的 React 應用程式設定前端。您可以使用這個 npm 指令。 ``` npm create -y vite frontend -- --template react-ts // once installed, you can check if it's running properly. cd frontend npm install npm run dev ``` 您可以使用此 npm 命令安裝 Wing。 ``` npm install -g winglang ``` 您可以使用`wing -V`驗證安裝。 Wing 還提供官方[VSCode 擴充功能](https://marketplace.visualstudio.com/items?itemName=Monada.vscode-wing)和[IntelliJ](https://plugins.jetbrains.com/plugin/22353-wing) ,後者提供語法突出顯示、補全、轉到定義和嵌入式 Wing 控制台支援。您可以在建立應用程式之前安裝它! 建立後端目錄。 ``` mkdir ~/shared-counter/backend cd ~/shared-counter/backend ``` 建立一個新的空 Wing 專案。 ``` wing new empty // This will generate three files: package.json, package-lock.json and main.w file with a simple "hello world" program wing it // to run it in the Wing simulator // The Wing Simulator will be opened in your browser and will show a map of your app with a single function. //You can invoke the function from the interaction panel and check out the result. ``` 使用指令`wing new empty`後的結構如下。 ``` bring cloud; // define a queue, a bucket, and a counter let bucket = new cloud.Bucket(); let counter = new cloud.Counter(initial: 1); let queue = new cloud.Queue(); // When a message is received in the queue -> it should be consumed // by the following closure queue.setConsumer(inflight (message: str) => { // Increment the distributed counter, the index variable will // store the value before the increment let index = counter.inc(); // Once two messages are pushed to the queue, e.g. "Wing" and "Queue". // Two files will be created: // - wing-1.txt with "Hello Wing" // - wing-2.txt with "Hello Queue" bucket.put("wing-{index}.txt", "Hello, {message}"); log("file wing-{index}.txt created"); }); ``` 您可以安裝`@winglibs/vite`來啟動開發伺服器,而不是使用`npm run dev`來啟動本機 Web 伺服器。 ``` // in the backend directory npm i @winglibs/vite ``` 您可以使用`backend/main.w`中提供的 publicEnv 將資料傳送到前端。 讓我們來看一個小例子。 ``` // backend/main.w bring vite; new vite.Vite( root: "../frontend", publicEnv: { TITLE: "Wing + Vite + React" } ); // import it in frontend // frontend/src/App.tsx import "../.winglibs/wing-env.d.ts" //You can access that value like this. <h1>{window.wing.env.TITLE}</h1> ``` 你還可以做更多: - 讀取/更新 API 路線並使用 Wing Simulator 檢查它。 - 使用後端獲取值。 - 使用`@winglibs/websockets`同步瀏覽器,它在後端部署一個 WebSocket 伺服器,您可以連接此 WebSocket 來接收即時通知。 您可以閱讀完整的逐步指南,以了解[如何使用 React 作為前端和 Wing 作為後端建立簡單的 Web 應用程式](https://www.winglang.io/docs/guides/react-vite-websockets)。測試是使用 Wing Simulator 完成的,並使用 Terraform 部署到 AWS。 部署後的AWS架構是這樣的。 ![建築學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/27awil840ktgh3jvklij.png) 為了提供開發者選擇和更好的體驗,Wing 推出了對[TypeScript (Wing)](https://www.winglang.io/docs/typescript/)等其他語言的全面支援。唯一強制性的事情是您必須安裝 Wing SDK。 這也將使控制台完全可用於本地偵錯和測試,而無需學習 Wing 語言。 Wing 甚至還有其他[指南](https://www.winglang.io/docs/category/guides),因此更容易遵循。 ![指南](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/31czxehkg10ezmlpf7ac.png) 您可以閱讀[文件](https://www.winglang.io/docs)並查看[範例](https://www.winglang.io/docs/category/examples)。 您也可以在[Playground](https://www.winglang.io/play/?code=LwAvACAAVABoAGkAcwAgAGkAcwAgAHQAaABlACAAaQBtAHAAbwByAHQAIABzAHQAYQB0AGUAbQBlAG4AdAAgAGkAbgAgAFcAaQBuAGcALgAKAC8ALwAgAEgAZQByAGUAIAB3AGUAIABiAHIAaQBuAGcAIAB0AGgAZQAgAFcAaQBuAGcAIABzAHQAYQBuAGQAYQByAGQAIABsAGkAYgByAGEAcgB5ACAAdABoAGEAdAAgAAoALwAvACAAYwBvAG4AdABhAGkAbgBzACAAYQBiAHMAdAByAGEAYwB0AGkAbwBuAHMAIABvAGYAIABwAG8AcAB1AGwAYQByACAAYwBsAG8AdQBkACAAcwBlAHIAdgBpAGMAZQBzAC4ACgBiAHIAaQBuAGcAIABjAGwAbwB1AGQAOwAKAAoALwAvACAAVABoAGkAcwAgAGMAbwBkAGUAIABkAGUAZgBpAG4AZQBzACAAYQAgAGIAdQBjAGsAZQB0ACAAYQBzACAAcABhAHIAdAAgAG8AZgAgAHkAbwB1AHIAIABhAHAAcAAuAAoALwAvACAAVwBoAGUAbgAgAGMAbwBtAHAAaQBsAGkAbgBnACAAdABvACAAYQAgAHMAcABlAGMAaQBmAGkAYwAgAGMAbABvAHUAZAAgAHAAcgBvAHYAaQBkAGUAcgAKAC8ALwAgAGkAdAAgAHcAaQBsAGwAIABiAGUAIABzAHUAYgBzAHQAaQB0AHUAdABlAGQAIABiAHkAIABhAG4AIABpAG0AcABsAGUAbQBlAG4AdABhAHQAaQBvAG4AIABmAG8AcgAKAC8ALwAgAHQAaABhAHQAIABjAGwAbwB1AGQALgAgAEkALgBlACwAIABmAG8AcgAgAEEAVwBTACAAaQB0ACAAdwBpAGwAbAAgAGIAZQAgAGEAbgAgAFMAMwAgAEIAdQBjAGsAZQB0AC4ACgBsAGUAdAAgAGIAdQBjAGsAZQB0ACAAPQAgAG4AZQB3ACAAYwBsAG8AdQBkAC4AQgB1AGMAawBlAHQAKAApADsACgAKAC8ALwAgACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAKAC8ALwAgAFkAbwB1ACAAYwBhAG4AIABpAG4AdABlAHIAYQBjAHQAIAB3AGkAdABoACAAdABoAGUAIABhAHAAcAAgAGkAbgAgAHQAaABlACAAYwBvAG4AcwBvAGwAZQAgAC0ALQA%2BAAoALwAvACAACgAvAC8AIABDAGwAaQBjAGsAIABvAG4AIAB0AGgAZQAgAEYAdQBuAGMAdABpAG8AbgAsACAAYQBuAGQAIAB0AGgAZQBuACAAaQBuAHYAbwBrAGUAIABpAHQAIABpAG4AIAB0AGgAZQAKAC8ALwAgAGwAbwB3AGUAcgAgAHIAaQBnAGgAdAAgAHAAYQBuAGUAbAAsACAAbwByACAAYwBsAGkAYwBrACAAbwBuACAAdABoAGUAIABCAHUAYwBrAGUAdAAKAC8ALwAgAHQAbwAgAHMAZQBlACAAaQB0AHMAIABjAG8AbgB0AGUAbgB0AHMAIABpAG4AIAB0AGgAZQAgAHAAYQBuAGUAbAAsACAAZQB0AGMALgAKAC8ALwAgACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAKAAoALwAvACAAYABpAG4AZgBsAGkAZwBoAHQAcwBgACAAcgBlAHAAcgBlAHMAZQBuAHQAIABjAG8AZABlACAAdABoAGEAdAAgAHIAdQBuAHMAIABsAGEAdABlAHIALAAgAG8AbgAKAC8ALwAgAG8AdABoAGUAcgAgAG0AYQBjAGgAaQBuAGUAcwAsACAAaQBuAHQAZQByAGEAYwB0AGkAbgBnACAAdwBpAHQAaAAgAGMAYQBwAHQAdQByAGUAZAAgAGQAYQB0AGEAIABhAG4AZAAKAC8ALwAgAHIAZQBzAG8AdQByAGMAZQBzACAAZgByAG8AbQAgAHQAaABlACAAcAByAGUALQBmAGwAaQBnAGgAdAAgAHAAaABhAHMAZQAuAAoAbABlAHQAIABoAGUAbABsAG8AXwB3AG8AcgBsAGQAIAA9ACAAaQBuAGYAbABpAGcAaAB0ACAAKAApACAAPQA%2BACAAewAKACAAIABiAHUAYwBrAGUAdAAuAHAAdQB0ACgAIgBoAGUAbABsAG8ALgB0AHgAdAAiACwAIAAiAEgAZQBsAGwAbwAsACAAVwBvAHIAbABkACEAIgApADsACgB9ADsACgAKAC8ALwAgAEkAbgBmAGwAaQBnAGgAdABzACAAYwBhAG4AIABiAGUAIABkAGUAcABsAG8AeQBlAGQAIABhAHMAIABzAGUAcgB2AGUAcgBsAGUAcwBzACAAZgB1AG4AYwB0AGkAbwBuAHMACgBuAGUAdwAgAGMAbABvAHUAZAAuAEYAdQBuAGMAdABpAG8AbgAoAGgAZQBsAGwAbwBfAHcAbwByAGwAZAApADsACgAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAACgAvAC8AIACRISAAUwB3AGkAdABjAGgAIABmAGkAbABlAHMAIABhAG4AZAAgAHMAZQBlACAAbwB0AGgAZQByACAAZQB4AGEAbQBwAGwAZQBzACAAdwBpAHQAaAAgAG0AbwByAGUACgAvAC8AIABlAHgAcABsAGUAbgBhAHQAaQBvAG4AcwAgAGEAYgBvAHYAZQAuAA%3D%3D)中使用 Wing 查看結構和範例。 如果你比較像輔導員。看這個! https://www.youtube.com/watch?v=wzqCXrsKWbo Wing 在 GitHub 上擁有超過 3500 個 Star,發布了 1500 多個版本,但仍未進入 v1 版本,這意味著意義重大。 去嘗試一下,做一些很酷的事情吧! https://git.new/wing-repo 星翼 ⭐️ --- 開發者生態系統不斷發展,許多開發者圍繞 React 建置了一些獨特的東西。 我不會介紹如何使用 React,因為這是一個非常廣泛的主題,我在最後貼了一些資源來幫助您學習 React。 但為了幫助您建立出色的 React 專案,我們介紹了 25 個開源專案,您可以使用它們來使您的工作更輕鬆。 這將有大量的資源、想法和概念。 我甚至會給你一些學習資源,以及一些產品的專案範例來學習 React。 一切都是免費的,而且只有 React。 讓我們涵蓋這一切! --- 1. [Mantine Hooks](https://www.npmjs.com/package/@mantine/hooks) - 用於狀態和 UI 管理的 React hooks。 -------------------------------------------------------------------------------------------- ![曼丁鉤子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g9gxhpt4zpmxgg2cfbqi.png) 這可能不是專門針對 React 的,但是您可以使用這些鉤子來使您的工作更輕鬆。這些鉤子隨時可用,每個鉤子都有許多選項。 如果我必須評價的話,這將是每個人都可以使用的最有用的專案,而不是從頭開始編寫程式碼。 相信我,獲得 60 多個 Hooks 是一件大事,因為他們有一個簡單的方法讓您可以透過簡單的文件查看每個 Hooks 的演示。 開始使用以下 npm 指令。 ``` npm install @mantine/hooks ``` 這就是如何使用`useScrollIntoView`作為 mantine 掛鉤的一部分。 ``` import { useScrollIntoView } from '@mantine/hooks'; import { Button, Text, Group, Box } from '@mantine/core'; function Demo() { const { scrollIntoView, targetRef } = useScrollIntoView<HTMLDivElement>({ offset: 60, }); return ( <Group justify="center"> <Button onClick={() => scrollIntoView({ alignment: 'center', }) } > Scroll to target </Button> <Box style={{ width: '100%', height: '50vh', backgroundColor: 'var(--mantine-color-blue-light)', }} /> <Text ref={targetRef}>Hello there</Text> </Group> ); } ``` 它們幾乎擁有從本地儲存到分頁、滾動視圖、交叉點,甚至一些非常酷的實用程式(例如滴管和文字選擇)的所有功能。這實在太有幫助了! ![滴管](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pighzv57fvyp5uxvw8dz.png) 您可以閱讀[文件](https://mantine.dev/hooks/use-click-outside/)。 如果您正在尋找更多選項,您也可以使用[替代庫](https://antonioru.github.io/beautiful-react-hooks/)。 他們在 GitHub 上擁有超過 23k star,但這不僅僅是為了 hooks,因為他們是 React 的元件庫。 隨著`v7`版本的發布,它的每週下載量已超過 38 萬次,這表明它們正在不斷改進且值得信賴。 https://github.com/mantinedev/mantine Star Mantine Hooks ⭐️ --- 2. [React Grid Layout](https://github.com/react-grid-layout/react-grid-layout) - 可拖曳且可調整大小的網格佈局,具有響應式斷點。 -------------------------------------------------------------------------------------------------------- ![反應網格佈局](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pyg7g1bm1d3hvkexrnh3.png) React-Grid-Layout 是專為 React 應用程式建構的響應式網格佈局系統。 透過支援可拖曳、可調整大小和靜態小部件,它提供了使用網格的簡單解決方案。 與 Packery 或 Gridster 等類似系統不同,React-Grid-Layout 不含 jQuery,確保輕量級且高效的實作。 它與伺服器渲染應用程式的無縫整合以及序列化和恢復佈局的能力使其成為開發人員在 React 專案中使用網格佈局的寶貴工具。 開始使用以下 npm 指令。 ``` npm install react-grid-layout ``` 這就是如何使用響應式網格佈局。 ``` import { Responsive as ResponsiveGridLayout } from "react-grid-layout"; class MyResponsiveGrid extends React.Component { render() { // {lg: layout1, md: layout2, ...} const layouts = getLayoutsFromSomewhere(); return ( <ResponsiveGridLayout className="layout" layouts={layouts} breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }} cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }} > <div key="1">1</div> <div key="2">2</div> <div key="3">3</div> </ResponsiveGridLayout> ); } } ``` 您可以閱讀[文件](https://github.com/react-grid-layout/react-grid-layout?tab=readme-ov-file#installation)並查看[演示](https://react-grid-layout.github.io/react-grid-layout/examples/0-showcase.html)。有一系列[演示](https://github.com/react-grid-layout/react-grid-layout?tab=readme-ov-file#demos),甚至可以透過點擊“查看下一個範例”來獲得。 您也可以嘗試[codesandbox](https://codesandbox.io/p/devbox/github/gilbarbara/react-joyride-demo/tree/main/?embed=1)上的東西。 該專案在 GitHub 上有超過 19k+ 的星星,有超過 16k+ 的開發者使用,並且[npm 套件](https://www.npmjs.com/package/react-grid-layout)的每週下載量超過 600k+。 https://github.com/react-grid-layout/react-grid-layout 明星 React 網格佈局 ⭐️ --- 3. [React Spectrum](https://github.com/adobe/react-spectrum) - 提供出色使用者體驗的程式庫和工具的集合。 ----------------------------------------------------------------------------------- ![反應譜](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b4wkgbdpd1gve36vgjne.png) React Spectrum 是一個庫和工具的集合,可幫助您建立自適應、可存取且強大的使用者體驗。 它們提供了太多的東西,以至於很難在一篇文章中涵蓋所有內容。 總的來說,他們提供了這四個庫。 ![反應譜](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m97vdq3x7nllmhyjy7p9.png) - [反應譜](https://react-spectrum.adobe.com/react-spectrum/index.html) - [React Stately](https://react-spectrum.adobe.com/react-stately/index.html) - 一組龐大的 React Hooks,為您的設計系統提供跨平台狀態管理。 - [反應詠嘆調](https://react-spectrum.adobe.com/react-aria/index.html) - [國際化](https://react-spectrum.adobe.com/internationalized/index.html) 我們將了解一些有關 React Aria 的內容,它是一個無樣式 React 元件和鉤子庫,可幫助您為應用程式建立可存取的、高品質的 UI 元件。 它經過了各種設備、互動方式和輔助技術的精心測試,以確保為所有用戶提供最佳體驗。 開始使用以下 npm 指令。 ``` npm i react-aria-components ``` 這就是建立自訂`select`的方法。 ``` import {Button, Label, ListBox, ListBoxItem, Popover, Select, SelectValue} from 'react-aria-components'; <Select> <Label>Favorite Animal</Label> <Button> <SelectValue /> <span aria-hidden="true">▼</span> </Button> <Popover> <ListBox> <ListBoxItem>Cat</ListBoxItem> <ListBoxItem>Dog</ListBoxItem> <ListBoxItem>Kangaroo</ListBoxItem> </ListBox> </Popover> </Select> ``` 相信我,出於學習目的,這是一座金礦。 ![選擇的設計結構](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndy61o8vtjjbq78e8vl8.png) 他們使用自己強大的[40 多個樣式元件](https://opensource.adobe.com/spectrum-css/),這比通常提供的要多得多。他們也有自己的一套[設計系統,](https://spectrum.adobe.com/)例如字體、UI、版面、動作等等。 ![造型元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a047jcb2ou7h057yf2d4.png) ![造型元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y1w5jq1vfbhd6o9c9ehm.png) 您可以詳細了解[Spectrum](https://react-spectrum.adobe.com/index.html)及其[架構](https://react-spectrum.adobe.com/architecture.html)。 他們在 GitHub 上擁有超過 11,000 顆星,這表明了他們的質量,儘管他們並不廣為人知。研究它們可以為您建立圖書館提供寶貴的見解。 https://github.com/adobe/react-spectrum Star React Spectrum ⭐️ --- 4.[保留 React](https://github.com/StaticMania/keep-react) - Tailwind CSS 和 React.js 的 UI 元件庫。 ------------------------------------------------------------------------------------------- ![保持反應](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5s2z1xig75on0j2gjt1g.png) Keep React 是一個基於 Tailwind CSS 和 React.js 建立的開源元件庫。它提供了一組多功能的預先設計的 UI 元件,使開發人員能夠簡化現代、響應式且具有視覺吸引力的 Web 應用程式的建立。 開始使用以下 npm 指令。 ``` npm i keep-react ``` 這就是使用時間軸的方法。 ``` "use client"; import { Timeline } from "keep-react"; import { CalendarBlank } from "phosphor-react"; export const TimelineComponent = () => { return ( <Timeline horizontal={true}> <Timeline.Item> <Timeline.Point icon={<CalendarBlank size={16} />} /> <Timeline.Content> <Timeline.Title>Keep Library v1.0.0</Timeline.Title> <Timeline.Time>Released on December 2, 2021</Timeline.Time> <Timeline.Body> Get started with dozens of web components and interactive elements. </Timeline.Body> </Timeline.Content> </Timeline.Item> <Timeline.Item> <Timeline.Point icon={<CalendarBlank size={16} />} /> <Timeline.Content> <Timeline.Title>Keep Library v1.1.0</Timeline.Title> <Timeline.Time>Released on December 23, 2021</Timeline.Time> <Timeline.Body> Get started with dozens of web components and interactive elements. </Timeline.Body> </Timeline.Content> </Timeline.Item> <Timeline.Item> <Timeline.Point icon={<CalendarBlank size={16} />} /> <Timeline.Content> <Timeline.Title>Keep Library v1.3.0</Timeline.Title> <Timeline.Time>Released on January 5, 2022</Timeline.Time> <Timeline.Body> Get started with dozens of web components and interactive elements. </Timeline.Body> </Timeline.Content> </Timeline.Item> </Timeline> ); } ``` 輸出如下。 ![時間軸元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v22pagugp45z68jap3en.png) 流暢的小動畫讓這一切都是值得的,如果你想快速建立一個 UI,沒有任何麻煩,你可以使用它。 ![上傳](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfy9f9w0nc6ipn6wigil.png) ![通知](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5zpwcnozi5ye3wpnev1g.png) 您可以閱讀[文件](https://react.keepdesign.io/docs/getting-started/Introduction)並查看[故事書](https://react-storybook.keepdesign.io/?path=/docs/components-accordion--docs)以進行詳細的使用測驗。 該專案在 GitHub 上有超過 1000 顆星,而且它的一些元件使用起來非常方便。 https://github.com/StaticMania/keep-react Star Keep React ⭐️ --- 5. [React Content Loader](https://github.com/danilowoz/react-content-loader) - SVG 支援的元件,可輕鬆建立骨架載入。 --------------------------------------------------------------------------------------------------- ![反應內容載入器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g8g2yc0zush5vfgwo6hv.png) 該專案為您提供了一個由 SVG 驅動的元件,可以輕鬆建立佔位符載入(如 Facebook 的卡片載入)。 在載入狀態期間使用骨架來向使用者指示內容仍在載入。 總的來說,這是一個非常方便的專案,可以增強整體使用者體驗。 開始使用以下 npm 指令。 ``` npm i react-content-loader --save ``` 您可以這樣使用它。 ``` import React from "react" import ContentLoader from "react-content-loader" const MyLoader = (props) => ( <ContentLoader speed={2} width={400} height={160} viewBox="0 0 400 160" backgroundColor="#f3f3f3" foregroundColor="#ecebeb" {...props} > <rect x="48" y="8" rx="3" ry="3" width="88" height="6" /> <rect x="48" y="26" rx="3" ry="3" width="52" height="6" /> <rect x="0" y="56" rx="3" ry="3" width="410" height="6" /> <rect x="0" y="72" rx="3" ry="3" width="380" height="6" /> <rect x="0" y="88" rx="3" ry="3" width="178" height="6" /> <circle cx="20" cy="20" r="20" /> </ContentLoader> ) export default MyLoader ``` ![輸出](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xnvqlf6fmg2fayd29ojr.png) 您甚至可以拖曳單一骨架或使用為 Facebook 和 Instagram 等不同社群媒體預先定義的骨架。 您可以閱讀[文件](https://github.com/danilowoz/react-content-loader?tab=readme-ov-file#gettingstarted)並查看[演示](https://skeletonreact.com/)。 該專案在 GitHub 上擁有 13k+ Stars,並在 GitHub 上有 45k+ 開發人員使用。 https://github.com/danilowoz/react-content-loader Star React 內容載入器 ⭐️ --- 6. [React PDF](https://github.com/diegomura/react-pdf) - 使用 React 建立 PDF 檔案。 ---------------------------------------------------------------------------- ![反應 pdf](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6jd7sz8eqda09rgjpf13.png) 該套件用於使用 React 建立 PDF。 開始使用以下 npm 指令。 ``` npm install @react-pdf/renderer --save ``` 您可以這樣使用它。 ``` import React from 'react'; import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer'; // Create styles const styles = StyleSheet.create({ page: { flexDirection: 'row', backgroundColor: '#E4E4E4', }, section: { margin: 10, padding: 10, flexGrow: 1, }, }); // Create Document Component const MyDocument = () => ( <Document> <Page size="A4" style={styles.page}> <View style={styles.section}> <Text>Section #1</Text> </View> <View style={styles.section}> <Text>Section #2</Text> </View> </Page> </Document> ); ``` ![輸出](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cb5fpfzijv3g5fi5utmw.png) ![輸出pdf分頁](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f46t80n0redm14icia1r.png) 您可以閱讀[文件](https://react-pdf.org/)並查看[演示](https://react-pdf.org/repl)。 React-pdf 現在提供了一個名為`usePDF`的鉤子,可以透過 React hook API 存取所有 PDF 建立功能。如果您需要更多控製文件的呈現方式或更新頻率,這非常有用。 ``` const [instance, update] = usePDF({ document }); ``` 該專案在 GitHub 上有 13k+ Stars,有超過 270 個版本,[每週下載量超過 400k](https://www.npmjs.com/package/@react-pdf/renderer) ,這是一個好兆頭。 https://github.com/diegomura/react-pdf Star React PDF ⭐️ --- 7. [Recharts](https://github.com/recharts/recharts) - 使用 React 和 D3 建立的重新定義的圖表庫。 -------------------------------------------------------------------------------- ![重新繪製圖表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i6817tmlix6n7wtgp1yq.png) 該庫的主要目的是幫助您輕鬆地在 React 應用程式中編寫圖表。 Recharts 的主要原則是。 1. 只需使用 React 元件進行部署即可。 2. 原生 SVG 支持,輕量級,僅依賴一些 D3 子模組。 3. 聲明性元件、圖表元件純粹是表示性的。 開始使用以下 npm 指令。 ``` npm install recharts ``` 您可以這樣使用它。 ``` <LineChart width={500} height={300} data={data} accessibilityLayer> <XAxis dataKey="name"/> <YAxis/> <CartesianGrid stroke="#eee" strokeDasharray="5 5"/> <Line type="monotone" dataKey="uv" stroke="#8884d8" /> <Line type="monotone" dataKey="pv" stroke="#82ca9d" /> <Tooltip/> </LineChart> ``` ![輸出](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uqtp999q1ahq8ajmvuwf.png) 您可以閱讀[文件](https://recharts.org/en-US/guide)並查看有關[Storybook](https://recharts.org/en-US/storybook)的更多資訊。 他們提供了大量的選項來自訂它,這就是開發人員喜歡它的原因。他們也提供一般常見問題的[wiki](https://github.com/recharts/recharts/wiki)頁面。 您也可以在此處的codesandbox 上嘗試。 https://codesandbox.io/embed/kec3v?view=Editor+%2B+Preview&module=%2Fsrc%2Findex.tsx 該專案在 GitHub 上有 22k+ Stars,有 200k+ 開發人員使用。 https://github.com/recharts/recharts 明星 Recharts ⭐️ --- 8. [React Joyride](https://github.com/gilbarbara/react-joyride) - 在您的應用程式中建立導遊。 ------------------------------------------------------------------------------- ![反應兜風](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ph7rt2bxqbxi67r47on8.png) ![反應兜風](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ov4wzohwszgv5v06cin4.png) 導覽是向新用戶展示您的應用程式或解釋新功能的絕佳方式。它改善了用戶體驗並可以創造個人化的觸感。 開始使用以下 npm 指令。 ``` npm i react-joyride ``` 您可以這樣使用它。 ``` import React, { useState } from 'react'; import Joyride from 'react-joyride'; /* * If your steps are not dynamic you can use a simple array. * Otherwise you can set it as a state inside your component. */ const steps = [ { target: '.my-first-step', content: 'This is my awesome feature!', }, { target: '.my-other-step', content: 'This another awesome feature!', }, ]; export default function App() { // If you want to delay the tour initialization you can use the `run` prop return ( <div> <Joyride steps={steps} /> ... </div> ); } ``` 它們還提供[元件列表](https://docs.react-joyride.com/custom-components)以及自訂預設用戶介面的簡單方法。 您可以閱讀[文件](https://docs.react-joyride.com/)並查看[演示](https://react-joyride.com/)。 您也可以嘗試[codesandbox](https://codesandbox.io/p/devbox/github/gilbarbara/react-joyride-demo/tree/main/?embed=1)上的東西。 他們在 GitHub 上有超過 6k 顆星,npm 套件每週下載量超過 25 萬次。 https://github.com/gilbarbara/react-joyride Star React Joyride ⭐️ --- 9. [SVGR](https://github.com/gregberge/svgr) - 將 SVG 轉換為 React 元件。 ------------------------------------------------------------------ ![svgr](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/94hpre3yl3ttu5zdexsv.png) SVGR 是一個將 SVG 轉換為 React 元件的通用工具。 它需要一個原始的 SVG 並將其轉換為隨時可用的 React 元件。 開始使用以下 npm 指令。 ``` npm install @svgr/core ``` 例如,您採用這個 SVG。 ``` <?xml version="1.0" encoding="UTF-8"?> <svg width="48px" height="1px" viewBox="0 0 48 1" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" > <!-- Generator: Sketch 46.2 (44496) - http://www.bohemiancoding.com/sketch --> <title>Rectangle 5</title> <desc>Created with Sketch.</desc> <defs></defs> <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="19-Separator" transform="translate(-129.000000, -156.000000)" fill="#063855" > <g id="Controls/Settings" transform="translate(80.000000, 0.000000)"> <g id="Content" transform="translate(0.000000, 64.000000)"> <g id="Group" transform="translate(24.000000, 56.000000)"> <g id="Group-2"> <rect id="Rectangle-5" x="25" y="36" width="48" height="1"></rect> </g> </g> </g> </g> </g> </g> </svg> ``` 執行SVGR後,將轉換為. ``` import * as React from 'react' const SvgComponent = (props) => ( <svg width="1em" height="1em" viewBox="0 0 48 1" {...props}> <path d="M0 0h48v1H0z" fill="currentColor" fillRule="evenodd" /> </svg> ) export default SvgComponent ``` 它使用[SVGO](https://github.com/svg/svgo)優化 SVG,並使用 Prettier 格式化程式碼。 將 HTML 轉換為 JSX 需要幾個步驟: 1. 將 SVG 轉換為 HAST (HTML AST) 2. 將 HAST 轉換為 Babel AST (JSX AST) 3. 使用 Babel 轉換 AST(重新命名屬性、更改屬性值…) 您可以在[Playground](https://react-svgr.com/playground/)閱讀[文件](https://react-svgr.com/docs/getting-started)並檢查內容。 該專案在 GitHub 上擁有 10k+ Stars,有超過 800 萬開發者使用,npm 上每週下載量超過 800k。 https://github.com/gregberge/svgr 明星 SVGR ⭐️ --- 10. [React Sortable Tree](https://github.com/frontend-collective/react-sortable-tree) - 用於巢狀資料和層次結構的拖放可排序元件。 ------------------------------------------------------------------------------------------------------------ ![反應可排序樹](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/907c4rnmev2wx1abq0r7.png) 一個 React 元件,支援對分層資料進行拖放排序。 ![反應可排序樹](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z4tm32vuteqaw5m7crag.png) 開始使用以下 npm 指令。 ``` npm install react-sortable-tree --save ``` 您可以這樣使用它。 ``` import React, { Component } from 'react'; import SortableTree from 'react-sortable-tree'; import 'react-sortable-tree/style.css'; // This only needs to be imported once in your app export default class Tree extends Component { constructor(props) { super(props); this.state = { treeData: [ { title: 'Chicken', children: [{ title: 'Egg' }] }, { title: 'Fish', children: [{ title: 'fingerline' }] }, ], }; } render() { return ( <div style={{ height: 400 }}> <SortableTree treeData={this.state.treeData} onChange={treeData => this.setState({ treeData })} /> </div> ); } } ``` 檢查由此獲得的各種[道具選項](https://github.com/frontend-collective/react-sortable-tree?tab=readme-ov-file#props)和[主題](https://github.com/frontend-collective/react-sortable-tree?tab=readme-ov-file#featured-themes)。 您可以閱讀[文件](https://github.com/frontend-collective/react-sortable-tree?tab=readme-ov-file#getting-started)並查看[Storybook](https://frontend-collective.github.io/react-sortable-tree/?path=/story/basics--minimal-implementation) ,以獲取一些基本和高級功能的演示。 它可能不會被積極維護(仍然沒有存檔),因此您也可以使用[維護的 fork 版本](https://github.com/nosferatu500/react-sortable-tree)。 該專案在 GitHub 上擁有超過 4,500 個 Star,並被超過 5,000 名開發人員使用。 https://github.com/frontend-collective/react-sortable-tree Star React 可排序樹 ⭐️ --- 11. [React Hot Toast](https://github.com/timolins/react-hot-toast) - 冒煙的 Hot React 通知。 -------------------------------------------------------------------------------------- ![反應熱吐司](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lw4veo990lspkchhwz64.png) React Hot Toast 透過簡單的自訂選項提供了驚人的 🔥 預設體驗。它利用 Promise API 進行自動加載,確保平穩過渡。 它重量輕,不到 5kb,但仍然可以存取,同時為開發人員提供了像`useToaster()`這樣的無頭鉤子。 首先將 Toaster 加入到您的應用程式中。它將負責渲染發出的所有通知。現在您可以從任何地方觸發 toast() ! 開始使用以下 npm 指令。 ``` npm install react-hot-toast ``` 這就是它的易用性。 ``` import toast, { Toaster } from 'react-hot-toast'; const notify = () => toast('Here is your toast.'); const App = () => { return ( <div> <button onClick={notify}>Make me a toast</button> <Toaster /> </div> ); }; ``` ![主題選項](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tl8ezjabacdllw8qnd41.png) ![主題選項](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zksldf8goqbytcuumhac.png) 他們有很多自訂選項,但`useToaster()`掛鉤為您提供了一個無頭系統,可以為您管理通知狀態。這使得建立您的通知系統變得更加容易。 您可以閱讀[文件](https://react-hot-toast.com/docs)、[樣式指南](https://react-hot-toast.com/docs/styling)並查看[示範](https://react-hot-toast.com/)。 該專案在 GitHub 上有 8k+ Stars,有 230k+ 開發者使用。 https://github.com/timolins/react-hot-toast Star React Hot Toast ⭐️ --- 12. [Payload](https://github.com/payloadcms/payload) - 建立現代後端+管理 UI 的最佳方式。 -------------------------------------------------------------------------- ![有效負載](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xev60f07ilzqlfdwni0p.png) Payload 是一個無頭 CMS 和應用程式框架。它旨在促進您的開發過程,但重要的是,當您的應用程式變得更加複雜時,不要妨礙您。 Payload 沒有黑魔法,完全開源,它既是一個應用程式框架,也是一個無頭 CMS。它確實是適用於 TypeScript 的 Rails,並且您會獲得一個管理面板。您可以使用此[YouTube 影片](https://www.youtube.com/watch?v=In_lFhzmbME)了解有關 Payload 的更多資訊。 https://www.youtube.com/watch?v=In\_lFhzmbME 您可以透過使用Payload來了解[其中涉及的概念](https://payloadcms.com/docs/getting-started/concepts)。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nqn1uqupsdkexoq913mm.png) 有效負載透過您選擇的資料庫適配器與您的資料庫進行互動。目前,Payload 正式支援兩種資料庫適配器: 1. MongoDB 與 Mongoose 2. Postgres 帶毛毛雨 開始使用以下命令。 ``` npx create-payload-app@latest ``` 您必須產生 Payload 金鑰並更新`server.ts`以初始化 Payload。 ``` import express from 'express' import payload from 'payload' require('dotenv').config() const app = express() const start = async () => { await payload.init({ secret: process.env.PAYLOAD_SECRET, express: app, }) app.listen(3000, async () => { console.log( "Express is now listening for incoming connections on port 3000." ) }) } start() ``` ![使用 nextjs 進行有效負載](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ghnnf34k70hpb0zjsf5f.png) 您可以閱讀[文件](https://payloadcms.com/docs/getting-started/what-is-payload)並查看[演示](https://demo.payloadcms.com/?_gl=1*9x0za3*_ga*NzEzMzkwNzIuMTcxMDE2NDk1MA..*_ga_FLQ5THRMZQ*MTcxMDE2NDk1MC4xLjEuMTcxMDE2NDk1MS4wLjAuMA..)。 他們還提供與 Payload + Stripe 無縫整合的[電子商務模板](https://github.com/payloadcms/payload/tree/main/templates/ecommerce)。此範本具有令人驚嘆的、功能齊全的前端,包括購物車、結帳流程、訂單管理等元件。 Payload 在 GitHub 上擁有 18k+ Stars,並且有超過 290 個版本,因此它們不斷改進,尤其是在資料庫支援方面。 https://github.com/payloadcms/payload 明星有效負載 ⭐️ --- 13. [React Player](https://github.com/cookpete/react-player) - 用於播放各種 URL 的 React 元件。 ------------------------------------------------------------------------------------- ![反應玩家](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/immw7vlgrdfbfxgts0a0.png) 用於播放各種 URL 的 React 元件,包括檔案路徑、YouTube、Facebook、Twitch、SoundCloud、Streamable、Vimeo、Wistia、Mixcloud、DailyMotion 和 Kaltura。您可以看到[支援的媒體](https://github.com/cookpete/react-player?tab=readme-ov-file#supported-media)清單。 ReactPlayer 的維護工作由 Mux 接管,這使它們成為一個不錯的選擇。 開始使用以下 npm 指令。 ``` npm install react-player ``` 您可以這樣使用它。 ``` import React from 'react' import ReactPlayer from 'react-player' // Render a YouTube video player <ReactPlayer url='https://www.youtube.com/watch?v=LXb3EKWsInQ' /> // If you only ever use one type, use imports such as react-player/youtube to reduce your bundle size. // like this: import ReactPlayer from 'react-player/youtube' ``` 您也可以使用`react-player/lazy`為您傳入的URL 延遲載入適當的播放器。這會為您的輸出加入幾個reactPlayer 區塊,但會減少主包的大小。 ``` import React from 'react' import ReactPlayer from 'react-player/lazy' // Lazy load the YouTube player <ReactPlayer url='https://www.youtube.com/watch?v=ysz5S6PUM-U' /> ``` 您可以閱讀[文件](https://github.com/cookpete/react-player?tab=readme-ov-file#props)並查看[演示](https://cookpete.github.io/react-player/)。他們提供了大量的選項,包括加入字幕並以簡單的方式使其響應。 它們在 GitHub 上擁有超過 8000 顆星,被超過 135,000 名開發人員使用,並且 npm 軟體包[每週的下載量超過 800k](https://www.npmjs.com/package/react-player) 。 https://github.com/cookpete/react-player 明星 React 播放器 ⭐️ --- 14. [Victory](https://github.com/FormidableLabs/victory) - 用於建立互動式資料視覺化的 React 元件。 ---------------------------------------------------------------------------------- ![勝利](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dbayfgbrutvffkk2slja.png) Victory 是一個可組合 React 元件的生態系統,用於建立互動式資料視覺化。 ![元件類型](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ua3jegboex4n21aid20.png) 開始使用以下 npm 指令。 ``` npm i --save victory ``` 您可以這樣使用它。 ``` <VictoryChart domainPadding={{ x: 20 }} > <VictoryHistogram style={{ data: { fill: "#c43a31" } }} data={sampleHistogramDateData} bins={[ new Date(2020, 1, 1), new Date(2020, 4, 1), new Date(2020, 8, 1), new Date(2020, 11, 1) ]} /> </VictoryChart> ``` 這就是它的渲染方式。他們還提供通常有用的動畫和主題選項。 ![勝利圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wdxztxui9zjtue0fz1jo.png) 您可以閱讀[文件](https://commerce.nearform.com/open-source/victory/docs)並按照[教學](https://commerce.nearform.com/open-source/victory/docs/native)開始。他們提供大約 15 種不同的圖表選項。 它也可用於[React Native(文件)](https://commerce.nearform.com/open-source/victory/docs/native) ,所以這是一個優點。我還建議您查看他們的常見[問題解答](https://commerce.nearform.com/open-source/victory/docs/faq#frequently-asked-questions-faq),其中描述了常見問題的程式碼解決方案和解釋,例如樣式、註釋(標籤)、處理軸。 該專案在 GitHub 上擁有 10k+ Stars,並在 GitHub 上有 23k+ 開發人員使用。 https://github.com/FormidableLabs/victory 勝利之星 ⭐️ --- 15. [React Slick](https://github.com/akiran/react-slick) - React 輪播元件。 ---------------------------------------------------------------------- ![反應圓滑](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4fn2aafcxs281yliyyv0.png) React Slick 是一個使用 React 建構的輪播元件。它是一個光滑的旋轉木馬的反應端口 開始使用以下 npm 指令。 ``` npm install react-slick --save ``` 這是使用自訂分頁的方法。 ``` import React, { Component } from "react"; import Slider from "react-slick"; import { baseUrl } from "./config"; function CustomPaging() { const settings = { customPaging: function(i) { return ( <a> <img src={`${baseUrl}/abstract0${i + 1}.jpg`} /> </a> ); }, dots: true, dotsClass: "slick-dots slick-thumb", infinite: true, speed: 500, slidesToShow: 1, slidesToScroll: 1 }; return ( <div className="slider-container"> <Slider {...settings}> <div> <img src={baseUrl + "/abstract01.jpg"} /> </div> <div> <img src={baseUrl + "/abstract02.jpg"} /> </div> <div> <img src={baseUrl + "/abstract03.jpg"} /> </div> <div> <img src={baseUrl + "/abstract04.jpg"} /> </div> </Slider> </div> ); } export default CustomPaging; ``` ![自訂分頁](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hh3qtgnftoapsrdx8w4y.png) 您可以閱讀有關可用的[prop 選項](https://react-slick.neostack.com/docs/api)和[方法](https://react-slick.neostack.com/docs/api#methods)的資訊。 您可以閱讀[文件](https://react-slick.neostack.com/docs/get-started)和所有帶有程式碼和輸出[的範例集](https://react-slick.neostack.com/docs/example/)。 他們在 GitHub 上有超過 11k 顆星,並且有超過 36 萬開發者在 GitHub 上使用它。 https://github.com/akiran/react-slick Star React Slick ⭐️ --- 16. [Medusa](https://github.com/medusajs/medusa) - 數位商務的建構模組。 ------------------------------------------------------------- ![美杜莎](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h7vd1qsx7l1jdsz2cnq0.png) Medusa 是一組商務模組和工具,可讓您建立豐富、可靠且高效能的商務應用程式,而無需重新發明核心商務邏輯。 這些模組可以客製化並用於建立高級電子商務商店、市場或任何需要基礎商務原語的產品。所有模組都是開源的,可以在 npm 上免費取得。 開始使用以下 npm 指令。 ``` npm install medusa-react @tanstack/[email protected] @medusajs/medusa ``` 將其包含在`app.ts`中。 只有 MedusaProvider 的子級才能從其鉤子中受益。因此,Storefront 元件及其子元件現在可以使用 Medusa React 公開的鉤子。 ``` import { MedusaProvider } from "medusa-react" import Storefront from "./Storefront" import { QueryClient } from "@tanstack/react-query" import React from "react" const queryClient = new QueryClient() const App = () => { return ( <MedusaProvider queryClientProviderProps={{ client: queryClient }} baseUrl="http://localhost:9000" > <Storefront /> </MedusaProvider> ) } export default App ``` 例如,這就是您如何使用突變來建立購物車。 ``` import { useCreateCart } from "medusa-react" const Cart = () => { const createCart = useCreateCart() const handleClick = () => { createCart.mutate({}) // create an empty cart } return ( <div> {createCart.isLoading && <div>Loading...</div>} {!createCart.data?.cart && ( <button onClick={handleClick}> Create cart </button> )} {createCart.data?.cart?.id && ( <div>Cart ID: {createCart.data?.cart.id}</div> )} </div> ) } export default Cart ``` 他們提供了一套電子商務模組(大量選項),例如折扣、價目表、禮品卡等。 ![電子商務模組](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x00lbkpny66esa1yep4u.png) 它們還提供了一種簡單的管理員和客戶身份驗證方法,您可以在[文件](https://docs.medusajs.com/)中閱讀。 他們提供了[nextjs 入門模板](https://docs.medusajs.com/starters/nextjs-medusa-starter)和[Medusa React](https://docs.medusajs.com/medusa-react/overview)作為 SDK。 該專案在 GitHub 上有 22k+ Stars,有 4k+ 開發者使用。 https://github.com/medusajs/medusa 明星美杜莎 ⭐️ --- 17. [React Markdown](https://github.com/remarkjs/react-markdown) - React 的 Markdown 元件. --------------------------------------------------------------------------------------- ![反應降價](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hcl4bq3m0r415mknvv5h.png) Markdown 至關重要,使用 React 渲染它對於各種場景都非常有用。 它提供了一個 React 元件,能夠安全地將一串 Markdown 渲染到 React 元素中。您可以透過傳遞外掛程式並指定要使用的元件而不是標準 HTML 元素來自訂 Markdown 的轉換。 開始使用以下 npm 指令。 ``` npm i react-markdown ``` 您可以這樣使用它。 ``` import React from 'react' import {createRoot} from 'react-dom/client' import Markdown from 'react-markdown' import remarkGfm from 'remark-gfm' const markdown = `Just a link: www.nasa.gov.` createRoot(document.body).render( <Markdown remarkPlugins={[remarkGfm]}>{markdown}</Markdown> ) ``` 等效的 JSX 是。 ``` <p> Just a link: <a href="http://www.nasa.gov">www.nasa.gov</a>. </p> ``` 他們還提供了一份[備忘錄](https://commonmark.org/help/)和一個十分鐘的逐步[教學](https://commonmark.org/help/tutorial/)。 ![教學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2oboj1ooemoo2j9uh2d7.png) 您可以閱讀[文件](https://github.com/remarkjs/react-markdown?tab=readme-ov-file#install)並查看[演示](https://remarkjs.github.io/react-markdown/)。 該專案在 GitHub 上有 12k+ Stars,[每週下載量超過 2700k](https://www.npmjs.com/package/react-markdown) ,並被 200k+ 開發人員使用,證明了它的真正有用性。 https://github.com/remarkjs/react-markdown Star React Markdown ⭐️ --- 18. [React JSONSchema Form](https://github.com/rjsf-team/react-jsonschema-form) - 用於從 JSON Schema 建立 Web 表單。 ------------------------------------------------------------------------------------------------------------ ![反應 jsonform 模式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/36bma59hylme02fg5mmi.png) `react-jsonschema-form`會自動從 JSON Schema 產生 React 表單,使其非常適合僅使用 JSON schema 為任何資料產生表單。它提供了像 uiSchema 這樣的自訂選項來自訂預設主題之外的表單外觀。 開始使用以下 npm 指令。 ``` npm install @rjsf/core @rjsf/utils @rjsf/validator-ajv8 --save ``` 您可以這樣使用它。 ``` import { RJSFSchema } from '@rjsf/utils'; import validator from '@rjsf/validator-ajv8'; const schema: RJSFSchema = { title: 'Todo', type: 'object', required: ['title'], properties: { title: { type: 'string', title: 'Title', default: 'A new task' }, done: { type: 'boolean', title: 'Done?', default: false }, }, }; const log = (type) => console.log.bind(console, type); render( <Form schema={schema} validator={validator} onChange={log('changed')} onSubmit={log('submitted')} onError={log('errors')} />, document.getElementById('app') ); ``` 他們提供[高級定制](https://rjsf-team.github.io/react-jsonschema-form/docs/advanced-customization/)選項,包括定制小部件。 您可以閱讀[文件](https://rjsf-team.github.io/react-jsonschema-form/docs/)並查看[即時遊樂場](https://rjsf-team.github.io/react-jsonschema-form/)。 它在 GitHub 上擁有超過 13k 個 Star,並被 5k+ 開發人員使用。他們在`v5`上發布了 190 多個版本,因此他們正在不斷改進。 https://github.com/rjsf-team/react-jsonschema-form Star React JSONSchema 表單 ⭐️ --- 19. [Craft.js](https://github.com/prevwong/craft.js) - 建立可擴充的拖放頁面編輯器。 --------------------------------------------------------------------- ![craft.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ydxmz82mswa2tlk5onbs.png) 頁面編輯器可以增強使用者體驗,但從頭開始建立頁面編輯器可能會令人望而生畏。現有庫提供具有可編輯元件的預先建置編輯器,但自訂通常需要修改庫本身。 Craft.js 透過模組化頁面編輯器元件、透過拖放功能簡化自訂以及渲染管理來解決這個問題。在 React 中設計你的編輯器,無需複雜的插件系統,專注於你的特定需求和規格。 開始使用以下 npm 指令。 ``` npm install --save @craftjs/core ``` 他們還提供了有關如何入門的[簡短教程](https://craft.js.org/docs/guides/basic-tutorial)。我不會介紹它,因為它非常簡單且詳細。 您可以閱讀[文件](https://craft.js.org/docs/overview)並查看[即時演示](https://craft.js.org/)以及另一個[即時範例](https://craft.js.org/examples/basic)。 它在 GitHub 上有大約 6k+ Stars,但考慮到它們正在改進,仍然很有用。 https://github.com/prevwong/craft.js Star Craft.js ⭐️ --- 20. [Gatsby](https://github.com/gatsbyjs/gatsby) - 最好的基於 React 的框架,具有內建的效能、可擴展性和安全性。 ------------------------------------------------------------------------------------ ![蓋茲比](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ybxi9gplvm2kr8abbtzy.png) Gatsby 是一個基於 React 的框架,使開發人員能夠建立閃電般快速的網站和應用程式,將動態渲染的靈活性與靜態網站生成的速度融為一體。 憑藉可自訂的 UI 和對各種資料來源的支援等功能,Gatsby 提供了無與倫比的控制和可擴展性。此外,它還可以自動進行效能最佳化,使其成為靜態網站的首選。 開始使用以下 npm 指令。 ``` npm init gatsby ``` 這就是如何在 Gatsby(反應元件)中使用`Link` 。 ``` import React from "react" import { Link } from "gatsby" const Page = () => ( <div> <p> Check out my <Link to="/blog">blog</Link>! </p> <p> {/* Note that external links still use `a` tags. */} Follow me on <a href="https://twitter.com/gatsbyjs">Twitter</a>! </p> </div> ) ``` 他們提供了一組[入門模板,](https://www.gatsbyjs.com/starters/)其中包含如何使用它、涉及的依賴項以及每個模板的演示。 ![範本](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8l35rwb1is60d5q506qu.png) 您可以閱讀有關 Gatsby 的一些[常見概念,](https://www.gatsbyjs.com/docs/conceptual/gatsby-concepts/)例如 React Hydration、Gatsby 建置流程等。 您可以閱讀[文件](https://www.gatsbyjs.com/docs/)並查看入門[教學課程](https://www.gatsbyjs.com/docs/tutorial/)。 Gatsby 在 GitHub 上擁有超過 55,000 顆星,並被超過 240,000 名開發者使用 https://github.com/gatsbyjs/gatsby 明星蓋茲比 ⭐️ --- 21. [Chat UI Kit React](https://github.com/chatscope/chat-ui-kit-react) - 在幾分鐘內使用 React 建立您的聊天 UI。 -------------------------------------------------------------------------------------------------- ![chatscope 聊天 ui 套件反應](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ynb25x1se0riwbvq5uv.png) Chatscope 的聊天 UI 工具包是一個用於開發網頁聊天應用程式的開源 UI 工具包。 儘管該專案並未廣泛使用,但這些功能對於剛剛查看該專案的初學者來說還是很有用的。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m1y87b1clbi00tojxgzi.png) 開始使用以下 npm 指令。 ``` npm install @chatscope/chat-ui-kit-react ``` 這就是建立 GUI 的方法。 ``` import styles from '@chatscope/chat-ui-kit-styles/dist/default/styles.min.css'; import { MainContainer, ChatContainer, MessageList, Message, MessageInput } from '@chatscope/chat-ui-kit-react'; <div style={{ position:"relative", height: "500px" }}> <MainContainer> <ChatContainer> <MessageList> <Message model={{ message: "Hello my friend", sentTime: "just now", sender: "Joe" }} /> </MessageList> <MessageInput placeholder="Type message here" /> </ChatContainer> </MainContainer> </div> ``` 您可以閱讀[文件](https://chatscope.io/docs/)。 故事書中有更[詳細的文件](https://chatscope.io/storybook/react/?path=/docs/documentation-introduction--docs)。 它提供了一些方便的元件,例如[`TypingIndicator`](https://chatscope.io/storybook/react/?path=/docs/components-typingindicator--docs) 、 [`Multiline Incoming`](https://chatscope.io/storybook/react/?path=/story/components-message--multiline-incoming)等等。 我知道你們中的一些人更喜歡透過部落格來了解整個結構,因此你可以閱讀使用 Chat UI Kit React 的 Rollbar 的[如何將 ChatGPT 與 React 整合](https://rollbar.com/blog/how-to-integrate-chatgpt-with-react/)。 您可以看到的一些演示: - [聊天機器人使用者介面](https://mars.chatscope.io/) - [與朋友聊天](https://chatscope.io/demo/chat-friends/)- 看看這個! ![聊天朋友演示快照](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hyhqti9yl02rludkocy.png) https://github.com/chatscope/chat-ui-kit-react Star Chat UI Kit React ⭐️ --- 22. [Botonic](https://github.com/hubtype/botonic) - 用於建立會話應用程式的 React 框架。 ------------------------------------------------------------------------- ![植物性的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yxeslrg9cjbkej0hcth4.png) Botonic 是一個全端 Javascript 框架,用於建立在多個平台上執行的聊天機器人和現代對話應用程式:Web、行動和訊息應用程式(Messenger、WhatsApp、Telegram 等)。它建構在 ⚛️ React、Serverless 和 Tensorflow.js 之上。 如果您不了解對話應用程式的概念,可以在[官方部落格](https://www.hubtype.com/blog/what-are-conversational-apps)上閱讀它們。 使用 Botonic,您可以建立包含最佳文字外介面(簡單性、自然語言互動)和圖形介面(多媒體、視覺上下文、豐富互動)的會話應用程式。 這是一個強大的組合,可以提供比僅依賴文字和 NLP 的傳統聊天機器人更好的用戶體驗。 這就是 Botonic 的簡單方式。 ``` export default class extends React.Component { static async botonicInit({ input, session, params, lastRoutePath }) { await humanHandOff(session)) } render() { return ( <Text> Thanks for contacting us! One of our agents will attend you as soon as possible. </Text> ) } } ``` 它們也支援 TypeScript,所以這是一個優點。 您可以看到一些使用 Botonic 建置的[範例](https://botonic.io/examples/)及其原始程式碼。 您可以閱讀[文件](https://botonic.io/docs/welcome)以及如何[從頭開始建立會話應用程式](https://botonic.io/docs/create-convapp)。 https://github.com/hubtype/botonic Star Botonic ⭐️ --- 23. [React Flowbite](https://github.com/themesberg/flowbite-react) - 為 Flowbite 和 Tailwind CSS 建構的 React 元件. ------------------------------------------------------------------------------------------------------------ ![反應流咬](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8vt1coti9k3ppmv0y28u.png) 每個人對他們想要用來建立網站的使用者介面都有不同的偏好。 Flowbite React 是 UI 元件的開源集合,在 React 中建置,具有來自 Tailwind CSS 的實用程式類,您可以將其用作使用者介面和網站的起點。 開始使用以下 npm 指令。 ``` npm i flowbite-react ``` 這是一起使用表格和鍵盤元件的方法。 ``` 'use client'; import { Kbd, Table } from 'flowbite-react'; import { MdKeyboardArrowDown, MdKeyboardArrowLeft, MdKeyboardArrowRight, MdKeyboardArrowUp } from 'react-icons/md'; function Component() { return ( <Table> <Table.Head> <Table.HeadCell>Key</Table.HeadCell> <Table.HeadCell>Description</Table.HeadCell> </Table.Head> <Table.Body className="divide-y"> <Table.Row className="bg-white dark:border-gray-700 dark:bg-gray-800"> <Table.Cell className="whitespace-nowrap font-medium text-gray-900 dark:text-white"> <Kbd>Shift</Kbd> <span>or</span> <Kbd>Tab</Kbd> </Table.Cell> <Table.Cell>Navigate to interactive elements</Table.Cell> </Table.Row> <Table.Row className="bg-white dark:border-gray-700 dark:bg-gray-800"> <Table.Cell className="whitespace-nowrap font-medium text-gray-900 dark:text-white"> <Kbd>Enter</Kbd> or <Kbd>Spacebar</Kbd> </Table.Cell> <Table.Cell>Ensure elements with ARIA role="button" can be activated with both key commands.</Table.Cell> </Table.Row> <Table.Row className="bg-white dark:border-gray-700 dark:bg-gray-800"> <Table.Cell className="whitespace-nowrap font-medium text-gray-900 dark:text-white"> <span className="inline-flex gap-1"> <Kbd icon={MdKeyboardArrowUp} /> <Kbd icon={MdKeyboardArrowDown} /> </span> <span> or </span> <span className="inline-flex gap-1"> <Kbd icon={MdKeyboardArrowLeft} /> <Kbd icon={MdKeyboardArrowRight} /> </span> </Table.Cell> <Table.Cell>Choose and activate previous/next tab.</Table.Cell> </Table.Row> </Table.Body> </Table> ); } ``` ![kbd 和表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mnu5xqlqob72t9oxkb4k.png) 您可以閱讀[文件](https://www.flowbite-react.com/docs/getting-started/introduction)並查看[Storybook](https://storybook.flowbite-react.com/?path=/story/components-accordion--always-open)中的功能。您也可以查看[元件](https://www.flowbite-react.com/docs/components/accordion)清單。 在我看來,如果您想快速設定 UI,但又不想最終為高品質的開源專案使用預先定義的庫元件,那麼這很好。 該專案在 GitHub 上擁有超過 1,500 顆星,擁有超過 37,000 名開發者的用戶群,並受到社群的廣泛認可和信任,使其成為一個可靠的選擇。 https://github.com/themesberg/flowbite-react Star React Flowbite ⭐️ --- 24. [DND 套件](https://github.com/clauderic/dnd-kit)- 輕量級、高效能、可存取且可擴展的拖放功能。 ------------------------------------------------------------------------- ![免打擾套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oz5m8hf4t4u4v2jzusl1.png) 這是一個強大的 React 拖放工具包,擁有可自訂的碰撞檢測、多個啟動器和自動滾動等功能。 它的設計考慮到了 React,提供了方便集成的鉤子,無需進行重大的架構更改。支援從清單到網格和虛擬化清單的各種用例,它既是動態的又是輕量級的,沒有外部相依性。 開始使用以下 npm 指令。 ``` npm install @dnd-kit/core ``` 這就是建立可拖放元件的方法。 `Example.jsx` ``` import React, {useState} from 'react'; import {DndContext} from '@dnd-kit/core'; import {Draggable} from './Draggable'; import {Droppable} from './Droppable'; function Example() { const [parent, setParent] = useState(null); const draggable = ( <Draggable id="draggable"> Go ahead, drag me. </Draggable> ); return ( <DndContext onDragEnd={handleDragEnd}> {!parent ? draggable : null} <Droppable id="droppable"> {parent === "droppable" ? draggable : 'Drop here'} </Droppable> </DndContext> ); function handleDragEnd({over}) { setParent(over ? over.id : null); } } ``` `Droppable.jsx` ``` import React from 'react'; import {useDroppable} from '@dnd-kit/core'; export function Droppable(props) { const {isOver, setNodeRef} = useDroppable({ id: props.id, }); const style = { opacity: isOver ? 1 : 0.5, }; return ( <div ref={setNodeRef} style={style}> {props.children} </div> ); } ``` `Draggable.jsx` ``` import React from 'react'; import {useDraggable} from '@dnd-kit/core'; import {CSS} from '@dnd-kit/utilities'; function Draggable(props) { const {attributes, listeners, setNodeRef, transform} = useDraggable({ id: props.id, }); const style = { // Outputs `translate3d(x, y, 0)` transform: CSS.Translate.toString(transform), }; return ( <button ref={setNodeRef} style={style} {...listeners} {...attributes}> {props.children} </button> ); } ``` 我將可拖曳元件放在可放置元件上。 ![自訂元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cf98be5hq9am3f2s1dwv.png) 您可以閱讀[文件](https://docs.dndkit.com/)以及滑鼠和指標等[感測器的選項](https://docs.dndkit.com/introduction/installation#core-library)。 它在 GitHub 上擁有 10k+ Stars,並被 GitHub 上 47k+ 開發人員使用。 https://github.com/clauderic/dnd-kit 明星免打擾套件 ⭐️