- 大家好,我是同學小張,日常分享AI知識和實戰(zhàn)案例
- 歡迎 點贊 + 關(guān)注 ??,持續(xù)學習,持續(xù)干貨輸出。
- +v: jasper_8017 一起交流??,一起進步??。
- 微信公眾號也可搜【同學小張】 ??
本站文章一覽:文章來源:http://www.zghlxwxcb.cn/news/detail-842220.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-842220.html
前面我們介紹了LangChain無縫銜接的LangSmith平臺,可以跟蹤程序運行步驟,提供詳細調(diào)試信息,同時支持數(shù)據(jù)集收集和自動化測試評估等功能,極大方便了AI大模型應用程序的開發(fā)過程。
本文來介紹另一款生產(chǎn)級AI應用維護平臺:LangFuse,它是開源的,是LangSmith 的平替,并且它可集成 LangChain,同時也可直接對接 OpenAI API。
官方網(wǎng)站:https://langfuse.com/
項目地址:https://github.com/langfuse
0. 環(huán)境準備
(1)先注冊,登錄,官網(wǎng)地址在上面
(2)創(chuàng)建Project
(3)生成私鑰和公鑰
一定要復制并記錄下這個私鑰和公鑰,關(guān)閉這個窗口后,私鑰就再也看不到了。
(4)本地安裝 langfuse
pip install --upgrade langfuse
1. 開始使用
LangFuse有兩種集成方式:
- OpenAI API集成
- LangChain集成
在運行之前,先將你的公鑰和私鑰放到環(huán)境變量中。例如.env文件中加入:
LANGFUSE_SECRET_KEY = "sk-lf-xxxxx"
LANGFUSE_PUBLIC_KEY = "pk-lf-xxxxx"
這樣才能使你的程序與你在LangFuse官網(wǎng)上建立的跟蹤項目鏈接起來。
不了解怎么寫.env文件的可以看下我前面的文章:【AI大模型應用開發(fā)】0. 開篇,用OpenAI API寫個Hello World !
1.1 OpenAI API集成方式
集成步驟:
(1)引入langfuse中的openai:from langfuse.openai import openai
,用這個才能集成langfuse
(2)使用Langfuse實例的trace函數(shù),傳入一些個人和項目信息
(3)openai接口調(diào)用,多了一個trace_id參數(shù)
from datetime import datetime
from langfuse.openai import openai ## 1. 引入langfuse中的openai
from langfuse import Langfuse
import os
## 2. 使用Langfuse實例的trace函數(shù),傳入一些個人和項目信息
trace = Langfuse().trace(
name = "hello-world",
user_id = "同學小張",
release = "v0.0.1"
)
completion = openai.chat.completions.create(
name="hello-world",
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "對我說'Hello, World!'"}
],
temperature=0,
trace_id=trace.id, ## 3. openai接口調(diào)用,多了一個trace_id參數(shù)
)
print(completion.choices[0].message.content)
## 輸出:Hello, World!
運行之后看下LangFuse平臺,應該能看到你的項目和調(diào)用了。
1.2 LangChain集成方式
通過 LangChain 的回調(diào)集成。
集成步驟:
(1)從langfuse中引入CallbackHandler:from langfuse.callback import CallbackHandler
(2)在CallbackHandler中設置個人和項目信息
(3)正常創(chuàng)建LangChain應用和流程
(4)invoke時,將CallbackHandler填入config參數(shù)中:config={"callbacks":[handler]}
from langfuse.callback import CallbackHandler
handler = CallbackHandler(
trace_name="SayHello",
user_id="同學小張",
)
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import RunnablePassthrough
from langchain.schema import HumanMessage
from langchain.prompts.chat import HumanMessagePromptTemplate
from langchain.prompts import ChatPromptTemplate
model = ChatOpenAI(model="gpt-3.5-turbo-0613")
prompt_template = """
我的名字叫【{name}】,我的個人介紹是【{description}】。
請根據(jù)我的名字和介紹,幫我想一段有吸引力的自我介紹的句子,以此來吸引讀者關(guān)注和點贊我的賬號。
"""
prompt = ChatPromptTemplate.from_messages([
HumanMessagePromptTemplate.from_template(prompt_template)
])
# 定義輸出解析器
parser = StrOutputParser()
chain = (
{"name":RunnablePassthrough(), "description":RunnablePassthrough() } ## 這里是給prompt的輸入,兩個參數(shù)
| prompt
| model
| parser
)
## invoke的第一個參數(shù),傳入json格式的參數(shù),key與prompt中的參數(shù)名一致
response = chain.invoke({'name': '同學小張', 'description': '熱愛AI,持續(xù)學習,持續(xù)干貨輸出'}, config={"callbacks":[handler]})
print(response)
運行之后看下LangFuse平臺,應該能看到你的項目和調(diào)用了。
2. 詳細信息查看 - Traces頁面
使用Traces頁面,可以看到你每次程序運行的詳細過程,包括每一步的輸入、輸出、耗時、token數(shù)等。
(1)進入Traces,可以看到你所有的運行目錄。
(2)點擊上方的任一ID,可以進入到本次運行的詳細跟蹤頁面。該頁面包含了本次運行的過程:詳細執(zhí)行步驟(右側(cè))。點擊任一步驟,可以在左側(cè)看到本步驟的輸入和輸出,以及耗時和token數(shù)(圖中的148->241表示輸入148token,輸出241token)。
有了這個頁面,你可以輕易的跟蹤輸入輸出是否有問題,哪一步有問題,從而更好的調(diào)優(yōu)你的程序。這個比自己打日志的信息更詳細和更好用多了。
3. 在線數(shù)據(jù)標注和收集
Langfuse與LangSmith一樣,也可以在線進行數(shù)據(jù)標注和收集。
(1)首先你需要先創(chuàng)建一個數(shù)據(jù)集的名稱。
(2)如果沒有事先創(chuàng)建數(shù)據(jù)集名稱,在下面這一步無法選擇dataset… 這是操作不如LangSmith的地方
(3)創(chuàng)建了數(shù)據(jù)集名稱之后,下面這一步就可以正常添加了
(4)然后你就可以看到你添加的數(shù)據(jù)集了
4. 本地數(shù)據(jù)集的導入
Langfuse除了支持在線的數(shù)據(jù)標注和收集,也支持從本地導入數(shù)據(jù)集。
以AGI課堂中的數(shù)據(jù)集例子給大家做演示。
數(shù)據(jù)集格式如下( .jsonl文件 ):outlines、user_input 以及 label字段,其中l(wèi)abel為標注,也就是輸出結(jié)果。
{"outlines": "Assistants API\n?1. OpenAI 給了我們更大空間\n?2. 原生 API、GPTs、Assistants API、國產(chǎn)/開源大模型選型參考\n?3. Assistants API 的主要能力\n?4. 做一個自己的 GPT\n 1. 創(chuàng)建 assistant\n 2. 管理 thread\n 3. 添加 message\n 4. 開始 run\n 5. 中控調(diào)度\n 6. Function Calling\n 7. Code Interpreter\n 8. RAG", "user_input": "別進reddit的中文話題,那是最沒營養(yǎng)的區(qū)域", "label": "N"}
{"outlines": "【神秘嘉賓】大模型時代的AI產(chǎn)品新挑戰(zhàn)\n1. AI 能力演進路線\n?2. LLMs 帶來的變化\n?3. 如何將大模型落地到實際場景中\(zhòng)n?4. LLMs 存在哪些問題\n?5. LLMs 落地三要素\n?6. LLMs 短期、中期和長期落地方向", "user_input": "對話式交互也不是所有場景都合適", "label": "N"}
接口:create_dataset_item
實現(xiàn)代碼:
import json
data = []
with open('D:\GitHub\LEARN_LLM\langsmith\my_annotations.jsonl','r',encoding='utf-8') as fp:
for line in fp:
example = json.loads(line.strip())
item = {
"input": {
"outlines": example["outlines"],
"user_input": example["user_input"]
},
"expected_output": example["label"]
}
data.append(item)
from langfuse import Langfuse
from langfuse.model import CreateDatasetRequest, CreateDatasetItemRequest
from tqdm import tqdm
# init
langfuse = Langfuse()
# 考慮演示運行速度,只上傳前5條數(shù)據(jù)
for item in tqdm(data[:5]):
langfuse.create_dataset_item(
dataset_name="assistant-data", ## 注意:這個dataset_name需要提前在Langfuse后臺創(chuàng)建
input=item["input"],
expected_output=item["expected_output"]
)
注意:dataset_name的名稱需要首先在langfuse平臺中手動創(chuàng)建。否則報錯:
運行成功后,langfuse中可以看到上傳的數(shù)據(jù):
5. 數(shù)據(jù)集的測試與評估
5.1 定義評估標準
這里定義一個簡單的標準,就是比較輸出和期望的結(jié)果是否一樣。
def simple_evaluation(output, expected_output):
return output == expected_output
5.2 定義Chain
在這里定義你的待評估的主要數(shù)據(jù)處理流程程序,也就是你的大模型應用。
from langchain.prompts import PromptTemplate
need_answer=PromptTemplate.from_template("""
*********
你是AIGC課程的助教,你的工作是從學員的課堂交流中選擇出需要老師回答的問題,加以整理以交給老師回答。
課程內(nèi)容:
{outlines}
*********
學員輸入:
{user_input}
*********
如果這是一個需要老師答疑的問題,回復Y,否則回復N。
只回復Y或N,不要回復其他內(nèi)容。""")
model = ChatOpenAI(temperature=0,model_kwargs={"seed":42})
parser = StrOutputParser()
chain_v1 = (
need_answer
| model
| parser
)
5.3 運行測試
下面的代碼中幾個關(guān)鍵點:
(1)ThreadPoolExecutor用來開啟線程池,并行測試數(shù)據(jù)集內(nèi)的測試數(shù)據(jù),可不用,串行測試即可,只是需要花更多時間。
(2)獲取數(shù)據(jù)集的接口: dataset = langfuse.get_dataset(dataset_name)
(3)通過callback與LangChain集成:handler = item.get_langchain_handler(run_name=run_name)
(4)評分:handler.root_span.score
,其中value為上面咱們自定義的評估標準函數(shù)
(5)本次測試的名稱:run_name
,也就是“v1-xxxxx”。
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from langfuse import Langfuse
langfuse = Langfuse()
def run_evaluation(chain, dataset_name, run_name):
dataset = langfuse.get_dataset(dataset_name)
def process_item(item):
handler = item.get_langchain_handler(run_name=run_name)
# Assuming chain.invoke is a synchronous function
output = chain.invoke(item.input, config={"callbacks": [handler]})
# Assuming handler.root_span.score is a synchronous function
handler.root_span.score(
name="accuracy",
value=simple_evaluation(output, item.expected_output)
)
print('.', end='',flush=True)
# Using ThreadPoolExecutor with a maximum of 10 workers
with ThreadPoolExecutor(max_workers=4) as executor:
# Map the process_item function to each item in the dataset
executor.map(process_item, dataset.items)
run_evaluation(chain_v1, "assistant-data", "v1-"+str(uuid.uuid4())[:8])
5.4 運行結(jié)果
測試結(jié)果:
每個數(shù)據(jù)的測試結(jié)果及詳情:
本文到這里就結(jié)束了,在本文中,我們?nèi)娼榻B了Langfuse平臺的基本功能:從程序運行監(jiān)控、跟蹤,到數(shù)據(jù)集的創(chuàng)建、建立自己的評估標準,再到實際運行一個測試,得到測試結(jié)果。簡單的使用,相信大家能對langfuse平臺有一個全面的認識。
如果覺得本文對你有幫助,麻煩點個贊和關(guān)注唄 ~~~
- 大家好,我是同學小張,日常分享AI知識和實戰(zhàn)案例
- 歡迎 點贊 + 關(guān)注 ??,持續(xù)學習,持續(xù)干貨輸出。
- +v: jasper_8017 一起交流??,一起進步??。
- 微信公眾號也可搜【同學小張】 ??
本站文章一覽:
到了這里,關(guān)于【AI大模型應用開發(fā)】【LangFuse: LangSmith平替,生產(chǎn)級AI應用維護平臺】0. 快速上手 - 基本功能全面介紹與實踐(附代碼)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!