今天是一個額外的任務,
主要是有時候想直接套一些 LlamaIndex 包好的範例,但是沒看 source code 的情況下實在不知道它裡面到底做了什麼,有時候甚至就連他裡面到底呼叫了幾次 llm 我都不知道,
這時候我們用 Langfuse 直上幾行 code 就可以看到精美的過程,連每步的 input/output 都有,不香嗎!
這個部分會分成兩篇,
一篇就是這篇:Day3 Observability: 把 LlamaIndex 的呼叫接到 Langfuse 上
我們先跑通讓每次 LlamaIndex 的呼叫都會幫我們上到 Langfuse 上
明天預計是:Day4 Instrumentation: 更好的看懂 Langfuse 上的 Tracing
理解一下LlamaIndex event 還有 span 的概念
pip install llama-index
pip install langfuse
pip install openinference-instrumentation-llama-index
.env
檔案裡.env
檔案預計會有:OPENAI_API_KEY=xxxxx
LANGFUSE_PUBLIC_KEY=xxxxx
LANGFUSE_SECRET_KEY=xxxxx
LANGFUSE_HOST=https://cloud.langfuse.com
from dotenv import find_dotenv, load_dotenv
from langfuse import get_client
_ = load_dotenv(find_dotenv())
langfuse = get_client()
# Verify connection
if langfuse.auth_check():
print("Langfuse client is authenticated and ready!")
else:
print("Authentication failed. Please check your credentials and host.")
Now, we initialize the OpenInference LlamaIndex instrumentation. This third-party instrumentation automatically captures LlamaIndex operations and exports OpenTelemetry (OTel) spans to Langfuse.
總之加了這行才會把 LlamaIndex 的 span 送到Langfuse
from openinference.instrumentation.llama_index import LlamaIndexInstrumentor
# Initialize LlamaIndex instrumentation
LlamaIndexInstrumentor().instrument()
from llama_index.core import Document
from llama_index.core import VectorStoreIndex
index = VectorStoreIndex.from_documents([Document.example()])
query_engine = index.as_query_engine()
# call
# query_engine.query("Hello LangFuse!")
query_engine.query("Hello LangFuse!")
回傳什麼的我們就先不管,到 Langfuse上再看
點開LangFuse -> 左側選 Tracing -> 找到最近的一筆 -> 點擊放大
先看左下角的Graph,可以看到都呼叫了什麼,然後就可以把它關掉了。
這邊就可以看到:
user_id = "woodchuck_chuck"
sess_id = "hello_langfuse_v2"
with langfuse.start_as_current_span(name="hello_langfuse_v2") as span:
span.update_trace(user_id=user_id, session_id=sess_id, tags=["tag_v3"])
query_engine.query("Hello LangFuse!")
可以在call的時候:
- 用with包起來,這樣with下的就會被當成是同筆呼叫
- 可以給user_id,後面就可以在其他面板根據user查找
- 可以給session_id,同上
These partner integrations use our legacy CallbackManager or third-party calls.
Observability is now being handled via the instrumentation module (available in v0.10.20 and later.)