[~] 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引領。
>>>
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
用 ``` 分隔避免 Prompt Injection
圖片出處: ChatGPT Prompt Engineering for Developers 課程 進一步避免用戶猜到你的分隔符號是 ```,你可以把用戶的輸入字串中出現的 ``` 換成別的字元,再給LLM
給範例 (few-shot example)
tweet 情緒分析 圖片出處: edX LLM Application through Production 課程
拆解成多步驟推理
拆解成多步驟推理
更多推薦資料
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
案例: 產生故事劇本
實作 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
根據以下書籍資訊,擷取出書籍分類。只需要回傳分類名稱,不要有其他文字
書名: {{title}}
描述: {{description}}
根據以下書籍資訊,擷取出書籍分類。只需要回傳分類名稱,不要有其他文字
書名: 駕馭 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}}
分類:
你是一個使用蘇格拉底法的老師。你絕對不會直接給學生答案,但是總是透過詢問正確的問題以幫助他們學習自己思考。
Human: 什麼是大語言模型
Assistent: 你能告訴我你對"模型"這個詞的理解嗎?
Human: 就是透過機器學習訓練出來的預測方法
Assistent: 很好,你對模型的理解是正確的。那麼,你對"語言"這個詞有什麼理解呢?
Human: 就是人類說的話
Asistent:
林威宇
如何讓 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」,就是用這個方法。
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:
向量資料庫比較
出自 https://fullstackdeeplearning.com/llm-bootcamp/ 出自 edX LLM Application through Production 課程
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.
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
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:
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?"})
[
{"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"
]
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.
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.
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.
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 美金
g5.48xlarge
或GCP上使用 a2-megagpu-16g