淺談 LLM 應用開發 Roadmap
一個全端開發者的觀點
@ALPHACamp AI Builder Day
2023/8/25
https://gai-2023.alphacamp.co/
因 GenAI 世界進步非常快速,請改閱讀以下最新完整版本

gamma.app

淺談 Generative AI Engineer 和 LLM 應用開發 Roadmap

合作開課單位:

以下內容為 2023/8/25 演講當時版本 snapshot,將不再繼續更新。
LLM 大語言模型
  • Large Language Model 大型語言模型
  • 用非常多語言資料來訓練的深度學習語言模型
  • ChatGPT 背後的關鍵技術,可以處理廣泛的自然語言任務(NLP)
  • 分類、摘要、翻譯、問答、情感分析、文本產生等等
  • 這個模型用戶輸入一句話(也就是提示詞 Prompt),模型可以預測下一句話(答案)
  • 和生成式AI (AIGC) 的關係是?
  • Generative AI 泛指所有可以 生成內容的 AI,包括文字、影像(Midjourney, Stable Diffusion 等)
  • 包括 LLM,這裡我們只談 LLM
我是誰
  • 張文鈿,網路暱稱 ihower
  • 2002 年開始從事 Web 軟體開發
  • 擅長使用 Ruby on Rails 技術,是個 Full-Stack Web Developer
  • 2018 年成立愛好資訊科技
  • 一個全端開發者 full-stack developer 的觀點,不是 Machine Learning Engineer 或 Data Scientist 觀點
若想進一步了解實做,歡迎報名我的 Workshop 課程
👉 歡迎訂閱我的 AI Engineer 電子報 aihao.eo.page/6tcs9
Roadmap
Part 1: 認識提示詞 Prompting
1
LLM API
了解 LLM API 的參數和限制
2
Prompt Techniques
如何寫好 Prompt
3
Prompt Engineering
工程思維和評估
Part 2: 四種常見應用場景
1
Conversation
Chatbot 對話應用
2
Summarization
長文本摘要轉換
3
Retriever Augmented
語意搜尋 和 QA 應用
4
Agent
自主決策的代理人
Part 3: 進階議題討論
1
LLM App Stack
了解工具和 LangChain
2
如何選擇模型
閉源 v.s. 開源
3
Fine-tuning
模型微調
4
LLM Hosting
模型部署
Roadmap Part 1: 提示詞
1
LLM API
了解 LLM API 的參數和限制
2
Prompt Techniques
如何寫好 Prompt
3
Prompt Engineering
工程思維和評估
把 LLM 當作一個 function
[~] python Python 3.11.3 (main, Apr 28 2023, 20:37:03) Type "help", "copyright", "credits" or "license" for more information. >>> import llm >>> model = llm.get_model("gpt-3.5-turbo") >>> response = model.prompt("寫一首關於AI的詩,50字以內") >>> print(response.text()) AI智慧,深入人心, 思維極速,無拘無束, 機器智慧,與我互動, 未來世界,AI引領。 >>>
  • 對 App developer 要寫 AI 應用來說,其實這樣就足夠了
  • 對 Machine Learning 專長的 Engineer 跟 Data Scientist 來說當然過於簡化

llm.datasette.io

Python API - LLM

LLM provides a Python API for executing prompts, in addition to the command-line interface.

LLM function 的參數有
  • 選 model 模型,例如 OpenAI 的 gpt-3.5-turbo 或是 gpt-4
  • prompt 提示詞
  • temperature 或 top_p 控制輸出的隨機性: 0.8 有創意、0.5 平衡、0.2 精準、0 總是一樣的回應
  • max_tokens 回應最多產生多少 token
  • 此 token 是切詞(sub-words)出來的單位,不同 model 有不同上限
Token 字數限制 (context window)
LLM 模型需將文字轉成編碼,才能訓練和輸出。方法是用 Sub-words 來切,而是不是用單字。
  • 1 token 大約是 4 英文字母
  • 100 token 大約是 75 words
  • 一個中文字約是 2 tokens
  • 不同LLM模型的最大可處理 tokens 數不同,例如
  • gpt3.5-turbo 是4k (包含 prompt 輸入和輸出)
  • gpt-4 是 8k
ChatGPT 是基於 LLM API 的應用 App
  • ChatGPT 是 LLM 的殺手級應用
  • ChatGPT 跟 OpenAI API 是分開的產品,分開綁信用卡付費
  • 我們 Application Developer 的定位是做 ChatGPT 應用層
  • 例如串在不同的 UI 渠道(Web App, Slack, LINE Messaging 等)、更多的資料整合、企業內應用等等
  • 另外補充
  • ChatGPT Plugins 是長在 ChatGPT 上,讓 ChatGPT 這個 App 呼叫你提供的 Plugin API。
  • ChatGPT Plugins Don't Have PMF,所以不建議去做了

Matt Rickard

ChatGPT Plugins Don't Have PMF

In a now-taken-down blog post summarizing an event with Sam Altman, Altman revealed that he doesn’t believe that ChatGPT plugins have product-market fit (outside of the browsing plugin) and won’t be coming to the API soon. Why? A few hypotheses (not mutually exclusive). Correct concept but not good enough yet: * GPT-4 picks the wrong plugins or fails to chain together multiple calls reliably. This is the major problem with most agent or plugin frameworks — they don’t work. They might be able

使用 LLM API 注意事項
1
模型是非確定性的
  • Prompt 沒有一定正確的寫法標準
  • 不同的 LLM 模型,表現不一樣、Prompt 也有差異
  • 有幻覺現象 (Hallucination) 可能會唬爛
2
API 是 Stateless 無狀態的
  • 每次你都得把所有對話歷史傳給 LLM API
3
Token 有長度限制 (Context Window)
  • Prompt 太長加上回應後,可能會超過限制
4
知識實時性 (有 cut-off date)
  • 模型只有到訓練當時的資料 (例如 OpenAI 是 2021/9),沒有新的內容,也沒有私人資料
5
LLM 本身不會用外部工具
  • LLM 本身不會連網自動去搜尋資料
6
LLM 還有安全性問題還沒完全解決
  • Prompt Injection
  • Jailbreaking
  • Prompt leaking
  • LLM Attacks

這些議題,代表工程團隊還有很多事情可做 😎
Roadmap Part 1: 提示詞
1
LLM API
了解 LLM API 的參數和限制
2
Prompt Techniques
如何寫好 Prompt
3
Prompt Engineering
工程思維和評估
推薦 ChatGPT Prompt Engineering for Developers 這課

deeplearningai_

ChatGPT Prompt Engineering for Developers - DeepLearning.AI

What you’ll learn in this course In ChatGPT Prompt Engineering for Developers, you will learn how to use a large language model (LLM) to quickly build new and powerful applications.  Using the OpenAI API, you’ll...

  • 指南 Guidelines
  • Principle 1: 寫清晰且具體的指示
  • Principle 2: 給模型思考時間
  • 常見基本用法示範
  • Summarizing 摘要
  • Inferring 推理
  • Transforming 文本轉換、翻譯
  • Expanding 擴寫
  • Chatbot 聊天機器人
1️⃣ 寫清晰且具體的指示
  • 清晰不代表短,Prompt 可以寫很長描述具體清楚
  • 用分隔符號來明確界定輸入的不同部分
  • 也可避免 Prompt injection: 用戶輸入一些 prompt 繞過你的指示,讓模型發出你不想做的事情

用 ``` 分隔避免 Prompt Injection

圖片出處: ChatGPT Prompt Engineering for Developers 課程 進一步避免用戶猜到你的分隔符號是 ```,你可以把用戶的輸入字串中出現的 ``` 換成別的字元,再給LLM

  • 可以指定輸出格式,例如指定 JSON 輸出
  • 指定滿足條件
  • 給範例 (這叫做 Few-shot prompt/learning,相比於 zero-shot)

給範例 (few-shot example)

tweet 情緒分析 圖片出處: edX LLM Application through Production 課程

2️⃣ 給模型思考時間
  • 給模型思考時間,指示模型對一個問題進行更長的思考時間
  • 若模型出現推理錯誤,你應該嘗試重新設計 prompt,要求要有一系列的推理
  • 太困難的任務,模型無法在短時間或用很少的詞來完成,就會亂掰
  • 這招叫做 Chain of Thought (CoT)
  • 也可以不拆步驟,只需要寫 Let's think step by step,就會大幅改進推理
  • 因為模型在預測 token 時,給每個 token 的計算時間都是一樣的

拆解成多步驟推理

拆解成多步驟推理

總結比較 Few-shot 和 CoT
推理能力由弱到強排列
更多 Prompting Techniques
  • Self-Consistency (Ensembling)
  • Self-Ask
  • Self-Criticism
  • Tree of Thoughts (ToT)

更多推薦資料

Building Systems with the ChatGPT API - DeepLearning.AI https://github.com/dair-ai/Prompt-Engineering-Guide https://learnprompting.org/docs/category/%EF%B8%8F-intermediate https://github.com/brexhq/prompt-engineering https://platform.openai.com/docs/guides/gpt-best-practices

Chaining Prompts
  • 多個任務時,雖然用一個 prompt 拆步驟也行(CoT),但若是複雜的任務,對 LLM 來說比較挑戰
  • 拆開 Prompts 一次只做一個任務,用 Prompt 的輸出作為下一個 Prompt 的(部分)輸入
  • 一環接一環,最後結果通常比較穩定,除錯也較容易
  • 雖然缺點是 API call latency 會變高
  • 若要串接使用外部工具,也只能用 Chaining,無法用 CoT

案例: 產生故事劇本

實作 Hierarchical Story Generation Chaining Prompts 輸入 故事 Summary 產生 Title 產生 Characters Summary + Characters 加一起,產生 Story Beats (故事節拍) Summary + Characters + Story Beats 加一起,產生 Location Summary + Characters + Story Beats + Location 加一起,產生 Dialogs

案例: 使用計算機工具

View more

Roadmap Part 1: 提示詞
1
LLM API
了解 LLM API 的參數和限制
2
Prompt Techniques
如何寫好 Prompt
3
Prompt Engineering
工程思維和評估
Prompt Engineering ≠ Blind Prompting

Mitchell Hashimoto

Prompt Engineering vs. Blind Prompting

簡陋的試錯(trial-and-error) 方式,不是 Engineering
不只有 Prompt Techniques,還有 Engineering
系統性的做 Iterative 迭代開發
  1. 準備 Dataset 測試資料集
  1. 準備幾個不同版本的 Prompt,嘗試不同的 Prompt Techniques
  1. 執行 Evaluation 評估 (或叫做 Testing)
以書籍分類過程為例
a. 準備書籍資料 Dataset
b. 準備數個 Prompts 來做實驗比較看看
其中 {{title}} 和 {{description}} 是自訂變數,會套用 Dataset 中的資料
候選一號: Zero-shot
根據以下書籍資訊,擷取出書籍分類。只需要回傳分類名稱,不要有其他文字 書名: {{title}} 描述: {{description}}
候選二號: Few-shot
根據以下書籍資訊,擷取出書籍分類。只需要回傳分類名稱,不要有其他文字 書名: 駕馭 ChatGPT 4: 探索 Azure OpenAI 與 Cognitive Service for Language 開發實踐 (使用.NET 與 Node.js) 描述: 2023年最熱門的關鍵詞無疑是「ChatGPT」。市面上充斥著各式各樣的導讀,指引你如何靈活運用ChatGPT。 分類: ChatGPT 書名: 重新認識 Vue.js:008天絕對看不完的 Vue.js 3 指南 描述: 從零開始!快速上手!網羅完整Vue.js功能的實戰指南 分類: Vue.js 書名: {{title}} 描述: {{description}} 分類:
c. 批次跑出結果,進行評估
  • 哪一個 Prompt 的效果比較好? 有多好?
  • token 數越多成本(cost 和 latency) 會越高,值得嗎?
  • 若改用更高級的模型 GPT-4 的結果會好多少?
  • 成本值得嗎? GPT-4 比 GPT3.5-Turbo 貴20~30倍、速度慢一倍
  • Zero-shot 的 GPT-4 v.s 用高級 Prompting 技巧花比較多 token 的 GPT3.5-Turbo
  • 哪一個划算?
No-code 工具可以參考我上個月的分享有評測

gamma.app

Prompt Engineering 工具評測

工具評測 介紹我最近探索的一些 no-code 線上工具 2023/7/12@Generative AI 小聚 ft. HappyDesigner Meetup

Roadmap Part 2 應用場景
1
Conversation
Chatbot 對話應用
2
Summarization
長文本摘要轉換
3
Retriever Augmented
語意搜尋 和 QA 應用
4
Agent
自主決策的代理人
LLM API 是 Stateless 無狀態的
這整個是一個 Prompt,每次呼叫 API,你都需要把對話紀錄全部傳過去,不然 LLM 不會記得你之前講了啥
你是一個使用蘇格拉底法的老師。你絕對不會直接給學生答案,但是總是透過詢問正確的問題以幫助他們學習自己思考。 Human: 什麼是大語言模型 Assistent: 你能告訴我你對"模型"這個詞的理解嗎? Human: 就是透過機器學習訓練出來的預測方法 Assistent: 很好,你對模型的理解是正確的。那麼,你對"語言"這個詞有什麼理解呢? Human: 就是人類說的話 Asistent:
Chatbot 聊天機器人
  • 聊天久了,會超過 LLM context-windows 字數上限,怎麼辦?
  • 各種策略,例如在 Langchain 這個 Python 套件提供有
  • ConversationBufferMemory 全部紀錄
  • ConversationBufferWindowMemory 只紀錄最近 N 筆
  • ConversationSummaryMemory 自動摘要前面的對話紀錄
  • ConversationSummaryBufferMemory 只紀錄最近 N 筆,更早前的紀錄用摘要
  • ConversationTokenBufferMemory 改用 Token 數判斷
不同方法的 Tokens 成長速度
Roadmap Part 2 應用場景
1
Conversation
Chatbot 對話應用
2
Summarization
長文本摘要轉換
3
Retriever Augmented
語意搜尋 和 QA 應用
4
Agent
自主決策的代理人
長文本摘要轉換
  • 摘要、文本轉換、資訊萃取,都屬於這種場景
  • 如果文本不長,一個 Prompt 就解決了。但是如果文本很長超過 tokens 限制,怎麼辦?
1. 鋸箭法
  • 只拿文本開頭去做摘要,後面就不管了
  • 蠻多做摘要的 Chrome extension 都這樣 😓😓😓
2. Map Reduce 法
  • 拆段落,每段做摘要(可平行處理)
  • 全部加總後,再做一次摘要
3. Refine 法
  • 第一段做摘要A
  • 第二段 + 摘要A 成為 摘要 B
  • 第三段 + 摘要B,成為摘要C
  • 以此類推
圖片出處: LangChain for LLM Application Development 課程
推薦閱讀

林威宇

如何讓 ChatGPT 摘要大量內容:不同方法的優缺點

讓 AI 做摘要是現在很常見的 AI 應用,但現在就算都使用 OpenAI,各家摘要的品質參差不齊。主要原因有兩個: AI 摘要結果不如預期的兩個原因 1. Prompt 這可能是最關鍵的問題。「摘要」這件事不如大家想得這麼單純,它要考慮的東西不少。 舉例來說,同樣一則台積電新聞,一般大眾和投資人關注的重點就不同。如果站在一般大眾的角度摘要重點,對投資人來說無用資訊太多,該講的重點沒講;如果站在投資人角度摘要,對一般大眾來說又省略太多前提,看不懂,也不了解為什麼這是重點。 「重點」是什麼,這很因人而異。一個人認為的重點,可能是另一個人眼中的廢話。所以你不能單純用「幫我摘要重點」作為 prompt。而要針對不同情境、不同使用者,特製該情境下的 prompt。 這也是為什麼大家會讓 ChatGPT 在做廣泛閱讀時做摘要,但回到自己專業領域,通常不會信任 ChatGPT 的摘要。因為前者就算是泛泛之論仍會有點收獲,但後者對摘要的品質要求變得很高。 2. 技術選擇 這邊要先了解一下目前技術的限制。現在最強的語言模型還是 OpenAI 的 GPT-4 和 GPT-3.5。 GPT-3.5 目前在摘要上最大的問題是一次能塞的內容少。他的限制是 4096 token,如果是寫滿字的 pdf,大概就是一頁半,而且理解能力較差。 GPT-4 的優點是理解能力強,但它的速度慢,如果閱讀長一點的文章,甚至會花到 2 分鐘以上。試想,你叫 AI 幫你摘要一篇文章,結果在那邊乾等 2 分鐘,顯然並不是很愉快的閱讀體驗。更別說 GPT-4 目前價格是 GPT-3.5 的 15 倍。就算你有錢有閒,基本的 GPT-4 token 上限是 8k (三頁 pdf),更貴的可以到 32k (12 頁 pdf),針對真的需要摘要的大量內容,這都是杯水車薪。 所以,針對超過字數限制的文件,有哪些摘要方法呢? 如何摘要大量內容 為了解決字數上限的問題,網路上有各式各樣的應對方法,這邊是我目前看到的幾種: 只拿開頭 有一款很紅的瀏覽器擴充功能——「YouTube & Article Summary powered by ChatGPT」,之前叫做「YouTube Summary with ChatGPT」,就是用這個方法。

5 Levels Of Summarization: Novice to Expert

github.com

Roadmap Part 2 應用場景
1
Conversation
Chatbot 對話應用
2
Summarization
長文本摘要轉換
3
Retriever Augmented
語意搜尋 和 QA 應用
4
Agent
自主決策的代理人
先講什麼是 Embedding?
  • 以 OpenAI API 提供的 Embedding API 為例
  • 給一段不超過 8192 token 的文字,回傳一個 1536 維度的向量 Vector 代表這文字的語意
  • 文字可以是一個單字、一個標題、一句話、一個段落、一篇文章
語意搜尋” (Semantic Search)
  • 餘弦相似性 (Cosine similarity) 可以找出最接近的 Vectors,就是最相似的內容
  • 將用戶的搜尋關鍵字,去找最相似的內容,就是語意搜尋了
  • 也可以拿來做推薦引擎,推薦相關的產品或是內容
舉例: 將書做 Embedding 後的多維向量,降到二維後視覺化
如何針對超長文本做 QA 問答?
(Chat with Your Data)
  • 學名: Retrieval-Augmented Generation (RAG)
  • 先搜尋出相關內容,放進 Prompt 裡面當作 context,再問 LLM
1. 準備工作
  • 先將文本資料拆段落 (chunks)
  • 每個段落建立 index,放到 Vector Database 向量資料庫
  • 若原始內容太鬆散(例如逐字稿),也可以先摘要再做索引
2. 當用戶問問題時
  • 根據問題做語意搜尋,找出 “問題字串” 和 “最相關的內容片段” 共 N 筆
  • 把 context 和問題組出 Prompt 再問 LLM
  • Prompt 範例:
the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer. {這裡放搜尋出來最相關的 context 資料} Question: {這裡放用戶問題} Helpful Answer:
流程圖
圖片出處: edX LLM Application through Production 課程
RAG 的系統元件
RAG 可以講的內容太多了….本質上其實是個資訊檢索 Information retrieval 問題
圖片出處: LangChain: Chat with Your Data 課程
  • 資料來源: 載入多種格式文件: CSV, File, HTML, Markdown, PDF 等
  • 各種拆 chunk 的方式: Text Splitters
  • LangChain 推薦的 RecursiveCharacterTextSplitter 方法最多人使用,需要設定 chunk 大小,以及前後重複多少
  • 各種 Vector Store (因為需要快速計算大量 vector 的 cosine 相似性)

向量資料庫比較

出自 https://fullstackdeeplearning.com/llm-bootcamp/ 出自 edX LLM Application through Production 課程

  • 各種 Embedding 算法 (不只有 OpenAI Embedding)
  • 各種 Retriever (不只有 Vector 相似性搜尋)
  • 例如 Hybrid 結合傳統全文搜尋 BM25 算法
  • LangChain 跟 LlamaIndex 套件中有不少方法可試
為何做 RAG?
因為想讓模型能夠回答特定領域知識
  • 模型的訓練資料只到某一個時間
  • 需要新的資料,或是放私人資料
  • 提供 LLM 相關的上下文,模型可以更好回答問題,避免幻覺
Q: 跟 Fine-tune 模型的方式相比?
Yes, 兩種方式都可以讓 LLM 回答特定領域知識,各有各的優缺點

Medium

Should you Prompt, RAG, Tune, or Train? A Guide to Choose the Right Generative AI Approach

Generative AI is moving at a face pace with organizations experimenting with this technology to solve their business problems. There are…

Q: 不是有出 100k context window 的 LLM? 還需要 RAG 嗎?
  • 研究指出,對於超長未經篩選的資料,不但 tokens 花費多成本高,效果也不好
  • LLM 對於開頭和結尾表現好,中間部分表現不好
  • 若能提供較少但更相關的內容,LLM 才能提供最佳結果

pinecone

Less is More: Why Use Retrieval Instead of Larger Context Windows

The idea of a large context window seems appealing at first — just give the model all your data and let it figure it out. However, Research shows that LLMs provide the best results when given fewer, more relevant documents in the context, rather than large numbers of unfiltered documents.

Roadmap Part 2 應用場景
1
Conversation
Chatbot 對話應用
2
Summarization
長文本摘要轉換
3
Retriever Augmented
語意搜尋 和 QA 應用
4
Agent
自主決策的代理人
Agent 應用
可區分兩大種類型
ReAct Agent
  • 我們告訴 LLM 有哪些工具可以用,讓 LLM 自行判斷是否需要使用
  • 從用戶問題中擷取出工具參數
  • 執行工具
  • 觀察工具輸出
  • 不斷重複直到問題解決

ReAct

ReAct: Synergizing Reasoning and Acting in Language Models 提出一種 Prompting 方式,可以進行連續推理和行動的代理人任務 圖片出處: edX 課程 Action: 根據用戶輸入,選擇應該用哪一個 Tool 就根據 tool 的文字描述來判斷 Action Input: 根據需要使用的 tool,從用戶輸入中提取參數 Observation: 觀察 Tool 得到的結果 Thought: 再看一次用戶輸入,判斷接下來怎麼辦 是回到 Action 用另一個工具? 還是這就是 Final Answer? Final Answer: Thought 看到 Observation 後,若認為這是解答,就給出最終輸出

LangChain 實做舉例解析

用法舉例 llm = OpenAI(temperature=0) tools = load_tools(["python_repl", "requests_all"], llm=llm) agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True) agent.run("請抓取解析 https://ihower.tw/test.json 這個 JSON,然後將裡面的 bar 的值,乘上 pi 回傳") 內部實作解析 request 工具的描述是 Prompt 樣版長這樣... 範例發出去的第一個 prompt: GPT 回傳片段 然後 langchain 用 requests_get 工具,用以上 Input 參數,去拿資料 將放到 Observation 裡面成為下一次的 Prompt 發出去的第二個 prompt: GPT 回傳片段 然後 langchain 用 Calculator 工具,用以上 Input 參數,用 Math chain 尋求解答 發出去的第三個 prompt: GPT 回傳片段 然後 langchain 用 math 工具,用以上 Input 參數,產生 python code 執行,算出 1230 1230 放到 Observation 裡面成為下一次的 Prompt 發出去的第四個 prompt GPT 回傳片段 結束 (花了四個 prompt 一堆 tokens…. 辛苦了)

OpenAI Function Calling 是個 killing feature

Function Calling 就是針對 ReAct 這個使用外部工具的需求,透過 Fine-Tune 模型出來的功能。因此不需要複雜的 ReAct Prompting 技巧囉。 將自然語言轉換為 API 呼叫,更方便可靠串接外部工具,LLM 回傳的就是結構化參數 告訴 LLM 你有哪些工具(Function)可以使用,讓 LLM 自己判斷要不要使用,要用的話回傳參數 可取代 ReAct 實作,就不需要 ReAct prompt 了 可以做 metadata 萃取,將非結構化資料,轉成結構化資料 目前只有 OpenAI 推出,但其他家我猜未來也都會提供,例如 Llama 2 就有人 fine-tuned 出來了 使用流程 呼叫API時,傳入你定義的 functions 名稱、描述、參數 這樣 API 會回傳你應該要呼叫哪一個function和參數(JSON format) 你內部呼叫那個 function 得到結果 Chat API 中的 role 多了一種叫做 function,把上述結果再發給 Chat API 得到最終結果可以給用戶看 Function calling and other API updates 使用案例一: 完整流程 以詢問天氣為例,LLM 沒有今天的天氣資料,但你自己有實作一個 get_current_weather 方法 Step 1: 發出 Prompt 請求,附上你有的 function 規格 { "model": "gpt-3.5-turbo-0613", "messages": [ {"role": "user", "content": "今天波士頓天氣如何?"} ], "functions": [ { "name": "get_current_weather", "description": "傳入地點,回傳目前天氣資訊", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市或地區" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } } ] } LLM 的回應 { "id": "chatcmpl-123", ... "choices": [{ "index": 0, "message": { "role": "assistant", "content": null, "function_call": { "name": "get_current_weather", "arguments": "{ \"location\": \"波士頓\"}" } }, "finish_reason": "function_call" }] } Step 2 你實際呼叫 get_current_weather 方法,帶有參數 location,得到一個結果 { "temperature": 22, "unit": "celsius", "description": "Sunny" } Step 3 再次呼叫 OpenAI API,除了原先的對話紀錄,多傳一個 role 是 function 的資料,把上述的天氣結果放進去 { "model": "gpt-3.5-turbo-0613", "messages": [ {"role": "user", "content": "今天波士頓天氣如何?"}, {"role": "assistant", "content": null, "function_call": {"name": "get_current_weather", "arguments": "{ \"location\": \"Boston, MA\"}"}}, {"role": "function", "name": "get_current_weather", "content": "{\"temperature\": "22", \"unit\": \"celsius\", \"description\": \"Sunny\"}"} ], "functions": [ { "name": "get_current_weather", "description": "傳入地點,回傳目前天氣資訊", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "城市或地區" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"] } }, "required": ["location"] } } ] } 回傳 { "id": "chatcmpl-123", ... "choices": [{ "index": 0, "message": { "role": "assistant", "content": "波士頓目前天氣晴朗,氣溫為攝氏22度。", }, "finish_reason": "stop" }] } 結束。 使用案例二: 只用來擷取資料 (fake function) 透過一個 fake function,你只需要一次 API 呼叫,目的是拿結構化的 function 參數 { "model": "gpt-3.5-turbo-0613", "messages": [ {"role": "user", "content": "Extract and save the relevant entities mentioned in the following passage together with their properties. Passage: {這裡放入你的文本}" } ], "functions": [ { "name": "information_extraction", "description": "Extracts the relevant information from the passage.", "parameters": { "type": "object", "properties": { "company_name": { "type": "string", "description": "文本中提到的公司名稱" }, "report_date": { "type": "string", "description": "文本的製作日期" }, }, "required": ["company_name", "report_date"] } } ], "function_call": { "name": "information_extraction" } } 回傳 { ... "choices": [{ "index": 0, "message": { "role": "assistant", "content": null, "function_call": { "name": "information_extraction", "arguments": "{ \"company_name\": \"愛好資訊科技\", \"report_date\": \"2023-08-21\"}" } }, "finish_reason": "function_call" }] } 其中 arguments 就是個結構化 JSON 資料 使用案例三: 自己就可以做 ReAct 出處 Santiago on Twitter

Plan-and-Execute Agent
  • 又叫做 Autonomous Agent 給目標自動執行
  • 目前最前沿的研究,不斷出新的實驗品 AutoGPT, BabyGPT, MetaGPT 等等
  • 由 LLM 自主驅動的代理人,自主思考和執行任務,成為通用問題解決者
史丹佛小鎮,觀察25個AI居民之間如何生活聊天

GitHub

GitHub - joonspk-research/generative_agents: Generative Agents: Interactive Simulacra of Human Behavior

Generative Agents: Interactive Simulacra of Human Behavior - GitHub - joonspk-research/generative_agents: Generative Agents: Interactive Simulacra of Human Behavior

進階閱讀: Autonomous Agent 的元件組成

Lil'Log

LLM Powered Autonomous Agents

Building agents with LLM (large language model) as its core controller is a cool concept. Several proof-of-concepts demos, such as AutoGPT, GPT-Engineer and BabyAGI, serve as inspiring examples. The potentiality of LLM extends beyond generating well-written copies, stories, essays and programs; it can be framed as a powerful general problem solver. Agent System Overview In a LLM-powered autonomous agent system, LLM functions as the agent’s brain, complemented by several key components:

Roadmap Part 3: 進階議題
1
LLM App Stack
了解工具和 LangChain
2
如何選擇模型
閉源 v.s. 開源
3
Fine-tuning
模型微調
4
LLM Hosting
模型部署
LLM App Stack (from a16z)

Andreessen Horowitz

Emerging Architectures for LLM Applications | Andreessen Horowitz

A reference architecture for the LLM app stack. It shows the most common systems, tools, and design patterns used by AI startups and tech companies.

我的不負責評論
參考網友評論
Loading...
LangChain

www.langchain.com

LangChain

LangChain’s flexible abstractions and extensive toolkit enables developers to harness the power of LLMs.

  • 目前最紅的 LLM 工具,讓你方便組裝使用各種工具
  • 為何叫做 chain ?
  • 因為可以 Chain of Calls 串接再一起
  • 可以做 Prompt Template 樣版
  • 有很多做好的工具,例如....
  • 整合多家不同 models 提供者
  • 多種記憶對話的實作
  • 各種不同來源載入不同文件格式的方式
  • 各種不同切割段落的方式
  • 各種不同 Vector 資料庫
  • 各種不同寫好的 Chaining,包括可使用各種外部工具
  • 各種 Agent 代理人
一個 LangChain 的 RAG 範例
from langchain.document_loaders import WebBaseLoader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.embeddings import OpenAIEmbeddings from langchain.vectorstores import Chroma from langchain.chains import RetrievalQA from langchain.chat_models import ChatOpenAI # 讀取資料 loader = WebBaseLoader("https://lilianweng.github.io/posts/2023-06-23-agent/") data = loader.load() # 拆段落 text_splitter = RecursiveCharacterTextSplitter(chunk_size = 500) all_splits = text_splitter.split_documents(data) # embedding 後,塞進 Vector Store vectorstore = Chroma.from_documents(documents=all_splits, embedding=OpenAIEmbeddings()) # 可以問問題了 llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0) RetrievalQA.from_chain_type(llm, retriever=vectorstore.as_retriever()) result = qa_chain({"query": "什麼是 Agent?"})
不到 10 行就可以做出一個 QA 應用,難怪各種 QA 應用層出不窮,但實際用下去結果好像普普?
Why not LangChain?

reddit

Langchain is pointless

It's filled with crap like this: for i in range(n_results, 0, -1): try: return self._collection.query( ...

news.ycombinator.com

Langchain Is Pointless | Hacker News

The #1 learning is that there is no reusability with the current generation of LLMs. We're using GPT-4 and 3.5T exclusively.

  • 過度複雜的解決方案,對於它試圖解決的問題而言,它似乎是不必要的。只需要會 HTTP call 就可以用 LLM,有需要框架嗎?
  • Prompt engineering is model-specific! 每個 LLM 表現都不一樣,沒有很好的重用性。但 LangChain 的抽象化設計,都用一樣的 Prompt 和 Chains 去解決問題,只會得到中庸的結果。
  • LangChain 隱藏了 Prompt,導致開發人員必須深入 Source code 和 Hacking 才能順利修改
  • 為了處理 Chaining 的文字解析,LangChain Source code 很複雜。但若用新的 OpenAI function calling 就可以結構化了,可以少掉非常多程式。
  • 到底是用 CoT 還是用 Prompt Chaining,LangChain 的設計更傾向後者來解決問題。因為前者需更依賴厲害的模型,而 LangChain 需要考量相容不同模型。
  • LangChain 很難調試 debug,即使使用 verbose=True 也是如此
  • LangChain 的極大受歡迎度正在扭曲整個 AI 生態系統,使其圍繞 LangChain 的工作流程。
  • 當然,有一些用戶認為,批評 LangChain 是不公平的,因為它是一個新的工具,仍然在發展中。
網友中肯評論
Loading...
我認為
  • LangChain 拿來做 PoC 用途非常方便好用
  • 但上 Production 完全可用自己熟悉的後端程式語言(例如 Node.js, Ruby, PHP, Go, Java, C#) 來實做
  • 我自己的專案用 Ruby on Rails 也是直接用 Ruby 呼叫 OpenAI API
  • 關鍵就是 Prompt 怎麼寫,怎麼 Chaining 起來,這些參考 LangChain 文件跟程式碼就可以學會了
Roadmap Part 3: 進階議題
1
LLM App Stack
了解工具和 LangChain
2
如何選擇模型
閉源 v.s. 開源
3
Fine-tuning
模型微調
4
LLM Hosting
模型部署
如何選擇模型?
首先,需要了解一下模型是如何訓練的:
1
預訓練模型
Pre-training model ,又叫做是 Foundation model 或 Base model
計算資源的巨大,學界很難做出來,都是業界在做
需要訓練好幾個月,花費上百萬美金
2
微調模型
將上述模型進行微調 Fine-tuned (需要數天),相對預訓練容易許多
微調之後的模型,還可以繼續用不同方式微調
Loading...
Base LLM 和 Instruction Tuned LLM 的回答差異
  • Base LLM 只是接龍
  • Instruction Tuned LLM 才會遵守指令,回答你要的內容
推薦 OpenAI 的這場 State of GPT 演講
  1. 預訓練階段: Base LLM 學會文字接龍
  1. 微調 SFT 階段: LLM 學會對話,此時可以當 AI 助手了
  1. 微調 RLHF (強化學習)階段: LLM 學會符合人類期待 (能更對齊人類需求: 有用、誠實、無害,但有 alignment tax 問題)

Microsoft Build

Microsoft Build: Highlights from 2023

Keep sharpening your skills with the event’s best on-demand sessions and find upcoming opportunities to spark your interest. Be sure to join us next year for the latest on developer innovations.

有哪些 LLM 模型?
閉源的 LLMs
  • OpenAI
  • 提供 Completion API (GPT-3 Base 模型)
  • babbage-002
  • davinci-002
  • 提供 Chat API
  • gpt-3-5-turbo (token 限制是 4k) 反應速度和價格比較好
  • gpt-3-5-turbo-16k
  • gpt-4 (token 限制是 8k) 是目前公認性能最好的也是最貴
  • gpt-4-32k (OpenAI 尚未開放,但 Azure OpenAI 可以排到喔)
  • Anthropic 的 Claude 系列 (要排隊申請),有 100k context window
  • claude-instant-1 速度更快
  • claude-2 推理更好
  • Google PaLM (要排隊申請)
  • 目前 API 尚不支援中文
開源的 LLMs

huggingface

Open LLM Leaderboard - a Hugging Face Space by HuggingFaceH4

Discover amazing ML apps made by the community

以下我們重點關注 Base model
  • Llama 2
  • 最多人關注,也是目前開源裡面最強的,可以商用
  • 大小有分 7B, 13B, 70B,以及 Chat 版本、HF 版本
  • 衍生的 fine-tuned 模型非常多,Open LLM Leaderboard 前 8 名都是 LLaMA 衍生後代
  • 目前有種 iOS v.s Android 的感覺
  • MPT (MosaicML被Databricks併購了)
  • Google T5 (老古董了)
  • Pythia
  • BLOOM
  • StableLM
  • Falcon
  • GLM (清华大学)
  • 族繁不及備載
昨晚(8/24)推出 Code Llama (針對Coding 的微調版本)

Meta

Introducing Code Llama, an AI Tool for Coding | Meta

We're releasing Code Llama, an AI model built on top of Llama 2 that's fine-tuned for generating and discussing code.

Chat fine-tuned 類型的 LLMs
  • 針對對話型錄,區分 role 來包裹對話
  • Role 有 system, user, assistant,可讓模型更遵守 system prompt 的指示
  • 注意: API 是 Stateless 無狀態沒有上下文關係的,因為每次呼叫API,都必須把對話全部傳過去
提供 Chat API,例如左邊的一個 Prompt 字串,變成右邊的 array 形式
OpenAI Chat API 再將上述 array 轉成 prompt 餵給 LLM
[ {"token": "<|im_start|>"}, "system\nYou are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.\nKnowledge cutoff: 2021-09-01\nCurrent date: 2023-03-01", {"token": "<|im_end|>"}, "\n", {"token": "<|im_start|>"}, "user\nHow are you", {"token": "<|im_end|>"}, "\n", {"token": "<|im_start|>"}, "assistant\nI am doing well!", {"token": "<|im_end|>"}, "\n", {"token": "<|im_start|>"}, "user\nHow are you now?", {"token": "<|im_end|>"}, "\n" ]
  • 其他家 LLM 也有出 Chat fine-tuned 版本
  • Meta LLama 2 用法
  • Google PaLM 也有分 text API 和 messages API
Function Calling fine-tuned 類型的 LLMs
除了 OpenAI 之外,其他家我認為也會陸續推出。
例如 LLama 2

Llama API

Home | Llama API

LLAMA API

GitHub

OpenAI-like function calling · Issue #463 · facebookresearch/llama

Hello guys! Thank you for great job! I&#39;m currently using OpenAI chat completions with function calling but OpenAI main models don&#39;t support fine-tuning yet but LLaMA does. Unfortunately Lan...

Roadmap Part 3: 進階議題
1
LLM App Stack
了解工具和 LangChain
2
如何選擇模型
閉源 v.s. 開源
3
Fine-tuning
模型微調
4
LLM Hosting
模型部署
如何 Fine-tuning?
Llama 2
可透過 HuggingFace 工具

huggingface

Llama 2 is here - get it on Hugging Face

We’re on a journey to advance and democratize artificial intelligence through open source and open science.

因為是開源模型,基於 LLama 的微調非常多,業界、學界很多人都在做
OpenAI API
  • 2023/8/23 宣布可以微調 GPT-3.5-Turbo,其他 GPT-3.5-Turbo-16k 和 GPT-4 再等等

OpenAI

GPT-3.5 Turbo fine-tuning and API updates

Developers can now bring their own data to customize GPT-3.5 Turbo for their use cases.

要不要自己 Fine-tune LLM?
為何你(可能)不需要 Fine-tune LLM

Tidepool by Aquarium

Why You (Probably) Don't Need to Fine-tune an LLM - Tidepool by Aquarium

In this post, we’ll talk about why fine-tuning is probably not necessary for your app, and why applying two of the most common techniques to the base GPT models — few-shot prompting and retrieval-augmented generation (RAG) — are sufficient for most use cases.

  • 大多數情境下其實用 Prompting (再加上 RAG) 就可以解決
  • 微調需要準備訓練資料(至少100筆以上資料)、花費計算資源,比起用 Prompting 成本跟難度要高
  • 建議先從 Prompting 開始看看能做到什麼程度
  • 什麼時候需要微調?
  • 當用 Prompting 太花 tokens 數時,微調後可以減少 few-shot 或指示文字
  • 當用 Prompting 需要的 inference time 太久
  • 當用 Prompting 對特定任務的的結果不夠穩定可靠時 ,例如輸出特定格式、風格語氣
OpenAI API 成本比較 (2023/8/23)
  • 使用微調版本比 GPT-3.5-Turbo 約貴了 8 倍
  • 使用 GPT-4 GPT-3.5-Turbo,約貴了 26 倍
  • GPT-4 比 GPT-3.5 微調,約貴了 3 倍
評論一(跟 gpt-3.5-turbo 比) 👎
Loading...
Conclusion: from a pure cost POV, the ONLY situation under which using GPT3 finetuning makes sense, is if you can realize the equivalent of 90% token savings at all scales! You have to be bet on SIGNIFICANT model performance improvements for the benefit to outweigh cost, because there is almost no realistic token savings scenario that makes it worth it.
評論二(跟 gpt-4 比) 👍
Loading...
Jerry: The key intuition : gpt-3.5-turbo (even after fine-tuning) is much cheaper than GPT-4 on a marginal token basis.
If we’re willing to incur a fixed cost through finetuning, then we can distill GPT-4 outputs to gpt-3.5-turbo in a cheaper package over your data.

這裡有個 Pro Tip: 你可以用高級模型來產生資料,當作低級模型微調的訓練資料
Stanford Alpaca model 就是這樣做出來的
OpenAI API 使用微調划算嗎?
  • 相比 GPT-3.5-Turbo,即使 Input Token 減少,幾乎不太可能用來省錢
  • 相比 GPT-4 ,若用微調可以達到比 GPT-3.5 Turbo Prompting 效果更好,提升到接近 GPT-4 就划算了
Roadmap Part 3: 進階議題
1
LLM App Stack
了解工具和 LangChain
2
如何選擇模型
閉源 v.s. 開源
3
Fine-tuning
模型微調
4
LLM Hosting
模型部署
LLM APIs and Hosting

透過這些 API 提供商,你不需要自己 Hosting 模型,而是根據 Tokens 數用量付費。
  • OpenAI API
  • 上手流程最簡單,註冊綁個信用卡即可拿到 api_key
  • Azure OpenAI API
  • 上手進 Azure 後台操作,比較複雜一點
  • API 認證參數不太一樣,其他則和 OpenAI 幾乎一模一樣
  • 有分不同地區: Australia East, Canada East, East US 2, Japan East, UK South
  • 推薦開通使用
  • HuggingFace Inference API
  • Pro 方案可以用 LLama 2 喔
Loading...
  • Google PaLM API
  • Google Cloud Platform 的 Vertex AI 內的 Generative AI Studio (這不用排隊)
  • AWS Bedrock 要申請排隊 (2023/9/28 已公開不用排隊了)
  • 模型有 Anthropic Claude, AI21, Amazon Titan, Cohere 和 Stability AI 的 Stable Diffusion 等
  • Llama 2 模型近期會推出
  • 其他 API Provider
給 ML 工程師的產品
有一些產品是給 Machine Learning 工程師團隊使用的,有完整的模型訓練、建構、部署的機器學習流程。這個部署和上述根據用量計費不同,這會部署一整台的專用伺服器,所費不貲。如果你只是 App deverloper 建議可以跳過了。
  • Azure Machine Learning
  • GCP Vertex AI
  • AWS SageMaker
展開說說 HuggingFace
  • 機器學習界的 Github,上面可以找到各種
  • Models
  • Datasets
  • Spaces (用來demos用)
  • 提供 Python Library 方便你使用模型
  • 提供各種 Deploy 方式

Python Library (下載模型到本機進行 inference 和 fine-tune)

from transformers import AutoTokenizer import transformers import torch model = "meta-llama/Llama-2-7b-chat-hf" tokenizer = AutoTokenizer.from_pretrained(model) pipeline = transformers.pipeline( "text-generation", model=model, torch_dtype=torch.float16, device_map="auto", ) sequences = pipeline( # 'I liked "Breaking Bad" and "Band of Brothers". Do you have any recommendations of other shows I might like?\n', "請幫我命名一個專業的科技公司名稱", do_sample=True, top_k=10, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id, max_length=100, ) for seq in sequences: print(f"Result: {seq['generated_text']}") Mac M1 Pro (32G Ram)實測可以跑的動 Llama-2-7b-chat-hf,雖然有點慢。

Inference API (用 HF 提供的 API)

Inference API (用 HF 提供的 API)

Inference Endpoints (HF 幫你部署到雲端)

自己部署一台這價錢是 13×24×30 = 每個月 $9360 美金

要不要自己 hosted LLM?
為何你(很可能)不需要自己 hosted LLM

Better Programming

You don’t need hosted LLMs, do you?

A comparison of self-hosted LLMs and OpenAI: cost, text generation quality, development speed, and privacy.

  • 需要的理由
  • 資安和隱私: 大企業需要放自己家裡,不想把資料傳給 OpenAI
  • 反應速度: OpenAI API 不總是穩定,而且有時候很慢 (可以考量換 Azure OpenAI)
  • 模型效能維持不變: 可以確保模型的表現穩定一致。OpenAI 不透明且會下架舊模型,有人提出 GPT-4 性能有下降
  • 沒有 Vendor lock-in 問題
  • 不需要的理由
  • OpenAI GPT-4 仍是目前公認表現最好的模型,沒有替代品
  • 開發速度: 呼叫 LLM API 很容易上手,不需要處理基礎設施
  • 初始成本
  • LLM API 用 token 計費,用多少算多少
  • 自己 hosted 的固定成本很高,以 Llama 2 70b 來說,每月大約要 TWD 30萬以上
  • 以使用 8x Nvidia A100 為例,在AWS上使用 g5.48xlarge 或GCP上使用 a2-megagpu-16g
  • AWS 每月 $17244 美金
  • GCP 每月 $6421 美金
最後分享兩個觀點
  • Prompting 是 AI 應用的革命
  • 新時代 AI Engineer 的崛起
1. Prompting 是 AI 應用的革命
  • 跟以往機器學習流程不同,呼叫 LLM 的使用門檻很低
  • LLM 是個通用模型,用 API 去呼叫即可,不需要從頭訓練模型
  • 而且從頭訓練起的成本上百萬美金
  • App Developer 會 Prompt 就可以做到之前要有 Machine Learning 團隊才能做到的事情
  • 而且現在做的又快又好
圖片出處: DeepLearning.AI 的 Building Systems with the ChatGPT API 課程
2. 新時代 AI Engineer 的崛起

www.latent.space

The Rise of the AI Engineer

Emergent capabilities are creating an emerging job title beyond the Prompt Engineer. Plus: Join 500 AI Engineers at our first summit, Oct 8-10 in SF!

  • swyx 的這篇文章提出在 AI 新時代出現的新職種 — AI 工程師 (AI Engineer)
  • 除了提示詞 Prompt,想把 LLM 整合進產品,還需要做 Chains、Embeddings、Vector Database、Agent 等等
  • 這些事情不是ML工程師、也不是科學家在做的事,而是應用面的實作
  • 例如:Github Co-pilot 是一個成功的產品,但背後的 Prompt 交互細節是經過不斷打磨出來的 UX
  • 我們以 LLM API 為界
  • 左端負責研發模型、微調模型,並提供 API
  • 右端則是新的 AI 工程師和全端工程師
  • 我預測越來越多全端工程師會逐漸掌握使用 LLM API 技能,誰叫我們是全端 😙
請多指教
個人部落格 https://ihower.tw
若想進一步了解實做,歡迎報名我的 Workshop 課程
👉 歡迎訂閱我的 AI Engineer 電子報 aihao.eo.page/6tcs9
Made with