日誌、追蹤與監控
當使用 Langchain 建構應用程式或代理程式時,您最終會進行多次 API 呼叫以滿足單一使用者請求。但是,當您想要分析這些請求時,它們不會被串聯起來。透過 Portkey,來自單一使用者請求的所有嵌入、完成和其他請求都將被記錄和追蹤到一個通用 ID,使您能夠完全了解使用者互動。
本筆記本作為逐步指南,說明如何使用 Langchain 應用程式中的 Portkey
記錄、追蹤和監控 Langchain LLM 呼叫。
首先,讓我們匯入 Portkey、OpenAI 和 Agent 工具
import os
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain_openai import ChatOpenAI
from portkey_ai import PORTKEY_GATEWAY_URL, createHeaders
在下方貼上您的 OpenAI API 金鑰。(您可以在這裡找到它)
os.environ["OPENAI_API_KEY"] = "..."
取得 Portkey API 金鑰
- 在此註冊 Portkey
- 在您的 儀表板 上,按一下左下角的個人資料圖示,然後按一下「複製 API 金鑰」
- 貼在下方
PORTKEY_API_KEY = "..." # Paste your Portkey API Key here
設定追蹤 ID
- 在下方設定您的請求的追蹤 ID
- 追蹤 ID 對於來自單一請求的所有 API 呼叫可以是通用的
TRACE_ID = "uuid-trace-id" # Set trace id here
產生 Portkey 標頭
portkey_headers = createHeaders(
api_key=PORTKEY_API_KEY, provider="openai", trace_id=TRACE_ID
)
定義要使用的提示和工具
from langchain import hub
from langchain_core.tools import tool
prompt = hub.pull("hwchase17/openai-tools-agent")
@tool
def multiply(first_int: int, second_int: int) -> int:
"""Multiply two integers together."""
return first_int * second_int
@tool
def exponentiate(base: int, exponent: int) -> int:
"Exponentiate the base to the exponent power."
return base**exponent
tools = [multiply, exponentiate]
照常執行您的代理程式。 唯一 的變更是我們現在將在請求中 包含上述標頭。
model = ChatOpenAI(
base_url=PORTKEY_GATEWAY_URL, default_headers=portkey_headers, temperature=0
)
# Construct the OpenAI Tools agent
agent = create_openai_tools_agent(model, tools, prompt)
# Create an agent executor by passing in the agent and tools
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke(
{
"input": "Take 3 to the fifth power and multiply that by thirty six, then square the result"
}
)
[1m> Entering new AgentExecutor chain...[0m
[32;1m[1;3m
Invoking: `exponentiate` with `{'base': 3, 'exponent': 5}`
[0m[33;1m[1;3m243[0m[32;1m[1;3m
Invoking: `multiply` with `{'first_int': 243, 'second_int': 36}`
[0m[36;1m[1;3m8748[0m[32;1m[1;3m
Invoking: `exponentiate` with `{'base': 8748, 'exponent': 2}`
[0m[33;1m[1;3m76527504[0m[32;1m[1;3mThe result of taking 3 to the fifth power, multiplying it by 36, and then squaring the result is 76,527,504.[0m
[1m> Finished chain.[0m
{'input': 'Take 3 to the fifth power and multiply that by thirty six, then square the result',
'output': 'The result of taking 3 to the fifth power, multiplying it by 36, and then squaring the result is 76,527,504.'}
記錄與追蹤在 Portkey 上的運作方式
記錄
- 透過 Portkey 發送您的請求可確保預設記錄所有請求
- 每個請求日誌都包含
timestamp
、model name
、total cost
、request time
、request json
、response json
和其他 Portkey 功能
- 追蹤 ID 與每個請求一起傳遞,並且在 Portkey 儀表板上的日誌中可見
- 如果您願意,也可以為每個請求設定 不同的追蹤 ID
- 您也可以將使用者回饋附加到追蹤 ID。有關此處的更多資訊
對於上述請求,您將能夠像這樣檢視完整的日誌追蹤
進階 LLMOps 功能 - 快取、標記、重試
除了記錄和追蹤之外,Portkey 還提供更多功能,為您現有的工作流程增加生產能力
快取
從快取回應用戶先前服務的查詢,而不是再次將它們發送到 OpenAI。比對確切的字串或語意相似的字串。快取可以節省成本並將延遲時間縮短 20 倍。文件
重試
自動重新處理任何不成功的 API 請求最多 5
次。使用 指數輪詢
策略,該策略間隔重試嘗試以防止網路過載。文件
標記
使用預定義的標記詳細追蹤和稽核每次使用者互動。文件