LangSmith 是一個強大的工具,可以幫助開發者追蹤、監控和分析語言模型應用程序的性能。下面我將介紹兩種基本的追蹤方式:追蹤 OpenAI 調用和追蹤整個應用程序。
1. 追蹤 OpenAI 調用 (Trace OpenAI calls)
這種方法主要用于追蹤對 OpenAI API 的調用,可以幫助您了解每個 API 調用的詳細信息、性能和結果。
from openai import OpenAI
from langsmith.wrappers import wrap_openai
import os
openai_client = wrap_openai(OpenAI(api_key = "",base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)
)
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGCHAIN_API_KEY"] = ""def retriever(query: str):results = ["Harrison worked at Kensho"]return resultsdef rag(question):docs = retriever(question)system_message = """Answer the users question using only the provided information below:{docs}""".format(docs="\n".join(docs))res= openai_client.chat.completions.create(messages=[{"role": "system", "content": system_message},{"role": "user", "content": question},],model="qwen-turbo",)print(res.choices[0].message.content)return resif __name__ == "__main__":rag("where did harrison work")
在這個例子中,wrap_openai
函數會自動追蹤所有通過包裝后的客戶端進行的 API 調用。這些調用會被記錄到 LangSmith 平臺,您可以在那里查看詳細信息。
2. 追蹤整個應用程序 (Trace entire application)
這種方法可以追蹤整個應用程序的流程,包括中間步驟和函數調用,提供更全面的視圖。
from openai import OpenAI
from langsmith import traceable
from langsmith.wrappers import wrap_openai
import os# 設置環境變量
os.environ["LANGSMITH_TRACING"] = "true" # 啟用全局追蹤
os.environ["LANGCHAIN_API_KEY"] = ""# 包裝 OpenAI 客戶端
openai_client = wrap_openai(OpenAI(api_key="",base_url="https://dashscope.aliyuncs.com/compatible-mode/v1")
)# 定義可追蹤的檢索函數
@traceable
def retriever(query: str):results = ["Harrison worked at Kensho"]return results# 定義可追蹤的 RAG 函數
@traceable
def rag(question):# 追蹤檢索步驟docs = retriever(question)# 構建系統消息system_message = """Answer the users question using only the provided information below:{docs}""".format(docs="\n".join(docs))# 追蹤 LLM 調用步驟return openai_client.chat.completions.create(messages=[{"role": "system", "content": system_message},{"role": "user", "content": question},],model="qwen-turbo",)if __name__ == "__main__":# 整個應用程序流程將被追蹤response = rag("where did harrison work")print(response.choices[0].message.content)
在這個例子中,我們使用了:
LANGSMITH_TRACING=true
環境變量來啟用全局追蹤@traceable
裝飾器來追蹤特定函數- 包裝的 OpenAI 客戶端來追蹤 API 調用
這樣,整個應用程序的流程都會被記錄下來,包括:
- 檢索函數的輸入和輸出
- RAG 函數的整個流程
- OpenAI API 調用的詳細信息
查看追蹤結果
完成追蹤后,您可以在 LangSmith 平臺 (https://smith.langchain.com/) 上查看詳細的追蹤信息,包括:
- 函數調用鏈
- 每個步驟的輸入和輸出
- 執行時間和性能指標
- API 調用的詳細信息
總結
- 追蹤 OpenAI 調用:使用
wrap_openai
包裝 OpenAI 客戶端,適合只關注 API 調用的場景。 - 追蹤整個應用程序:使用
LANGSMITH_TRACING=true
和@traceable
裝飾器,適合需要全面了解應用程序流程的場景。