之前看到了網(wǎng)友的分享,講解了 chatpdf 的原理,但是并沒有看懂,不明白embeding 和completion 是什么意思,于是想著利用 chatgpt 學(xué)習(xí)一下,學(xué)習(xí)完之后一不做二不休,不如直接利用 chatgpt 寫一個玩具版的 chatpdf。
1. 需求
首先我們有一個 pdf,文章內(nèi)容 article_text,即背景信息文本為:
“這篇文章是關(guān)于運動的好處。鍛煉已被證明可以改善身體健康、心理健康和整體福祉。經(jīng)常鍛煉的人不太可能患上慢性疾病,如肥胖癥、糖尿病和心臟病。鍛煉還可以改善情緒,降低壓力水平。”
其次我們有一個問題文本 question_text,內(nèi)容為:
“這篇文章的主題是什么?”
問題是背景信息太冗長,所以我們要找到文章中與問題最相關(guān)的那部分內(nèi)容,然后將這部分內(nèi)容與問題發(fā)送給chatgpt,讓 chatgpt 根據(jù)這段內(nèi)容,對問題進行回答。
在我們的例子中,文章中與問題“這篇文章的主題是什么?”最相關(guān)的內(nèi)容,明顯是“這篇文章是關(guān)于運動的好處?!边@句話。
最后我們發(fā)送請求詢問chatgpt:這篇文章是關(guān)于運動的好處。請根據(jù)以上信息回答問題,這篇文章的主題是什么?
2. 原理
下面針對和我一樣聽不懂的小白,講一下 chatpdf 的實現(xiàn)原理:
- 將pdf中的文本讀取后并分為N段,則得到一個長度為n的數(shù)組
subtexts - 求出問題文本對應(yīng)的向量
embedding_question,至于這個向量是什么,你可以理解為文本的特征。(你不需要懂怎么求這個向量,只需要向 openai 發(fā)送請求即可,這個任務(wù)由 openai 完成,稱為embedding) - 遍歷前面N段文本即數(shù)組
subtexts,依次求出每段文本文本的向量,第 i 段文本對應(yīng)的向量為embedding_sub -
(重點)找出N段文本中,與問題文本最相似的那段文本。即求出向量
embedding_question與每個embedding_sub向量夾角的余弦值,并找出值最大的那段文本subtext[i]。是不是很懵?為什么余弦值能代表相似度,不要著急,后面會解釋 - 將文本
subtext[i]作為背景信息,讓 chatgpt 根據(jù)以上信息,回答問題question_text。
舉個栗子,如下圖所示,x 軸代表最炫民族風(fēng),y 軸代表雞你太美,向量r=(3, 4) ,表示用戶 r 對兩首歌曲的評分是 3 和 4,用戶 g 評分是 4 和 3,用戶 b 的評分是 5 和 0。不難理解,用戶 r 和用戶 g 的品位更加相似,因此可以將g 喜歡的其他歌曲推薦給 r ,但用戶 r 和 b 品位相差較大,則不該將小黑子 b 喜歡的歌曲推薦給 r 。

那么問題來了,如何用數(shù)學(xué)語言來描述兩個用戶的品位相似程度呢?
從圖中可以看到,相似的用戶向量夾角總是很小,相差較大的用戶向量夾角則很大。那么我們計算夾角的余弦值不就可以表示用戶的相似程度了嗎?
夾角度數(shù)為 90,余弦值為 0,表示二者完全不相關(guān);隨著夾角度數(shù)的減小,二者越來越相似,直至夾角度數(shù)為 0,余弦值為 1,表示二者完全相同;
那么系統(tǒng)就可以通過計算不同用戶間的余弦值,發(fā)現(xiàn)用戶向量 r 與 g 的夾角余弦值較大,因此會將 g 喜歡的其他歌曲推薦給 r 。
下面是求向量a與向量b夾角的余弦值公式①:

同樣的道理,我們也可以根據(jù)這個原理,找到文章中與問題最相關(guān)的那部分內(nèi)容。至此,我們已經(jīng)了解了 chatpdf 的工作原理。
3. 實現(xiàn)
我們就可以根據(jù)上面的思路,讓chatgpt完成編碼,最終編碼結(jié)果如下
第1部分,求出問題文本對應(yīng)的向量,將文章切分成多個子段
import openai
# 設(shè)置 OpenAI API 密鑰
openai.api_key = "sk-xxxx"
# 定義要查找相似部分的兩個文本
question_text = "What is the main topic of this article?"
article_text = "This article is about the benefits of exercise. Exercise has been shown to improve physical health, mental health, and overall well-being. People who exercise regularly are less likely to develop chronic diseases, such as obesity, diabetes, and heart disease. Exercise can also improve mood and reduce stress levels."
# 將問題文本question_text傳遞給 Embedding API,獲取它們的向量表示
response_question = openai.Embedding.create(model="text-embedding-ada-002", input=question_text)
embedding_question = np.array(response_question["data"][0]["embedding"])
# 將文本B劃分成多個子段
subtexts = article_text.split(". ")
第2部分,遍歷所有子段,找出與問題最相關(guān)的子段。這段代碼的關(guān)鍵部分就是求問題向量與子段向量夾角的余弦值。將上一節(jié)的余弦公式①用代碼表示,分子是兩個向量點乘,分母是兩個向量的模相乘,就可以求出兩個向量夾角的余弦值,即相似度。
similarity = np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
# 計算文本A與每個子段的相似度,找到相似度最高的子段
max_similarity = -1
max_subtext = ""
# 遍歷分段后的子段
for subtext in subtexts:
# 請求openai,得到子段的特征向量
response_sub = openai.Embedding.create(model="text-embedding-ada-002", input=subtext)
embedding_sub = np.array(response_sub["data"][0]["embedding"])
# (重點)求問題文本與子段的相關(guān)度, 即求兩個向量的余弦值
similarity = np.dot(embedding_question, embedding_sub) / (np.linalg.norm(embedding_question) * np.linalg.norm(embedding_sub))
# 找出與問題文本最相似的子段
if similarity > max_similarity:
max_similarity = similarity
max_subtext = subtext
# 輸出相關(guān)度最高的子段
print("Most similar subtext:", max_subtext)
print("-------------------------------------")
輸出結(jié)果如下,可以看到,成功找到了與問題最相關(guān)的子段:
Most similar subtext: This article is about the benefits of exercise
-------------------------------------
第3部分,將最相關(guān)子段和問題發(fā)給chatgpt,讓其作出回答:
# 提出問題, 根據(jù)子段max_subtext, 回答問題question_text
prompt = f"{max_subtext}. According to the information provided above, what is the answer to the following question: {question_text} "
print("Question:", prompt)
# 調(diào)用 OpenAI GPT-3 API,根據(jù)問題生成回答
response3 = openai.Completion.create(
model="text-davinci-003",
prompt=prompt
)
# 輸出回答
print("Answer:", response3.choices[0].text.strip())
輸出結(jié)果如下,可以看到,由于我們將與問題最相關(guān)的文本內(nèi)容,發(fā)送給了 chatgpt,所以 chatgpt 正確回答了問題:
Question: This article is about the benefits of exercise. According to the information provided above, what is the answer to the following question: What is the main topic of this article?
Answer: The main topic of this article is the benefits of exercise.