Skip to content

LlamaIndex

For a LlamaIndex app, install the extra and start the app with ctxflow-instrument. The extra brings the OpenInference instrumentation of LlamaIndex, which creates the agent and workflow, LLM, tool and retriever spans; ctxflow activates it for you.

Terminal window
pip install "ctxflow-otel[llamaindex]==0.2.2" # llama-index-core 0.14.19 or later, below 0.15
Terminal window
OTEL_SERVICE_NAME=my-agent \
OTEL_EXPORTER_OTLP_ENDPOINT=https://app.ctxflow.sh \
OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer%20<your key>" \
ctxflow-instrument python app.py

What you add yourself is the identity of the turn (ctxflow_otel.conversation(...), Identity) and the source identity in the metadata of your documents (Source identity).

You have Read
A FunctionAgent, AgentWorkflow or any Workflow Agents and workflows
A retriever or query engine Retrievers and tools
Tools that call your vector store directly Retrievers and tools
An ingestion pipeline, or your own splitter Ingestion
An MCP server’s tools Tools served over MCP
Google Gemini Models and tokens

Only ctxflow-instrument turns the LlamaIndex instrumentation on. init() and attach() do not (what each level does). With init(), start it yourself, after init(), with the helper of the SDK:

import ctxflow_otel
from ctxflow_otel.llamaindex import instrument_llamaindex
provider = ctxflow_otel.init()
instrument_llamaindex() # embedding text and vectors hidden, as under ctxflow-instrument

It does nothing if llama-index-core or the [llamaindex] extra is missing, or if llama_index is in OTEL_PYTHON_DISABLED_INSTRUMENTATIONS. If you prefer your own settings, start LlamaIndexInstrumentor().instrument(tracer_provider=provider, config=TraceConfig(hide_embeddings_text=True, hide_embeddings_vectors=True), skip_dep_check=True) yourself: skip_dep_check=True is needed, because without it OpenTelemetry skips the instrumentor in a normal app and no LlamaIndex span leaves the process.

  • Text leaves as the app wrote it. Under ctxflow-instrument, embedding text and vectors are always hidden. To hide more, set the OpenInference variables, for example OPENINFERENCE_HIDE_INPUTS=true (this hides prompts too, so the turn detail shows no text). Under ctxflow-instrument your own LlamaIndexInstrumentor().instrument(config=...) call has no effect, because the instrumentor already runs: use the variables.
  • Opt out with OTEL_PYTHON_DISABLED_INSTRUMENTATIONS=llama_index, for example when you start the instrumentor yourself.
  • A skipped instrumentor is not silent. If an installed instrumentor did not run, ctxflow-instrument logs a WARNING that names it: Python SDK.

Complete example in two scripts. It needs no model key (a mock model and a mock embedding). The ctxflow.source_* keys in the document metadata are what ctxflow uses to say which document a chunk came from and whether it was current (Source identity).

First build and save the index. Run it with plain python build_index.py, outside the agent, as you would in a separate indexing job. (To also see this step in ctxflow, instrument it as an ingestion pipeline: Ingestion.)

build_index.py
import ctxflow_otel
from llama_index.core import Document, Settings, VectorStoreIndex
from llama_index.core.embeddings import MockEmbedding
Settings.embed_model = MockEmbedding(embed_dim=8)
original = "# Shipping\nShipping takes 3 to 5 days.\n" # the file as it is on disk
doc = Document(
text="Shipping takes 3 to 5 days.",
id_="kb-shipping",
metadata={
"ctxflow.source_id": "kb/shipping.md",
"ctxflow.source_version": "v3",
"ctxflow.source_hash": ctxflow_otel.source_hash(original),
},
)
VectorStoreIndex.from_documents([doc]).storage_context.persist("storage")

Then the agent, which loads the index and answers one question:

app.py
import ctxflow_otel
from llama_index.core import Settings, StorageContext, load_index_from_storage
from llama_index.core.embeddings import MockEmbedding
from llama_index.core.llms import MockLLM
Settings.llm = MockLLM()
Settings.embed_model = MockEmbedding(embed_dim=8)
index = load_index_from_storage(StorageContext.from_defaults(persist_dir="storage"))
engine = index.as_query_engine(similarity_top_k=1)
with ctxflow_otel.conversation("conv-1", user_id="u1", turn=0): # the identity of the turn
print(engine.query("How long does shipping take?"))
Terminal window
python build_index.py
ctxflow-otel check
ctxflow-instrument python app.py

Run ctxflow-otel check first (Verify your setup). In the app, conv-1 shows one turn with one retrieved chunk of kb/shipping.md. Keep the conversation(...) block around each user turn: LlamaIndex work outside it, such as building an index inside the traced process, shows up as turns without a conversation.

FunctionAgent.run and the workflow steps are spans of kind CHAIN. ctxflow takes the outermost one as the turn, so you add no span of your own, and it does not matter that a web framework’s HTTP span comes first: How ctxflow finds the turn. Only identity is left to you. In a FastAPI handler:

import ctxflow_otel
from fastapi import FastAPI
from llama_index.core.agent.workflow import FunctionAgent
app = FastAPI() # run: ctxflow-instrument uvicorn app:app
agent = FunctionAgent(tools=[search_documents], llm=my_llm) # your tools and model
@app.post("/api/chat")
async def chat(question: str, conversation_id: str, user_id: str) -> dict[str, str]:
with ctxflow_otel.conversation(conversation_id, user_id=user_id):
answer = await agent.run(question)
return {"answer": str(answer)}
  • Streaming. agent.run(...) returns a handler that is already running: call it inside conversation(...) and read handler.stream_events() outside the block. Do not keep the block open across a yield: Streaming and async generators.
  • The answer. ctxflow shows the output.value of the turn span as it is. For a workflow whose root span carries the StopEvent(...) text, that text is the answer shown. Only when the turn span has no output does ctxflow use the output of the last model call. Set output.value yourself if you want a cleaner answer (Agent turns).
  • One turn per trace. One HTTP request, one question.
  • A LlamaIndex retriever or query engine already produces a retriever span with the documents, so you need no retrieval span of your own around it. If you add one anyway, ctxflow counts the retrieval once.
  • A tool that queries the vector store itself (a FunctionTool that calls vector_store.aquery(...)) produces a tool span but no retriever span: ctxflow sees a tool call and no chunks. Write the retrieval span inside the tool: A manual retrieval span.
  • What the chunks need. The ctxflow.source_* keys in the node metadata, so the retriever returns them (Source identity).

The same extra instruments ingestion: IngestionPipeline, VectorStoreIndex.from_documents, node parsers, and direct writes with vector_store.add. With init() or ctxflow-instrument in the ingestion process it stamps the chunks and reports the index writes: Ingestion: LlamaIndex. If you split text yourself and build the nodes, see Your own splitter and direct vector store writes.

To give a LlamaIndex FunctionAgent the tools of an MCP server, use llama-index-tools-mcp: pip install "ctxflow-otel[llamaindex,mcp]==0.2.2" llama-index-tools-mcp (see Install sources). Start the server under ctxflow too, and give it the telemetry variables with child_env:

First the server, server.py, with mcp 2.x (it runs over stdio, which is how the client below starts it):

from mcp.server.mcpserver import MCPServer
server = MCPServer("kb")
@server.tool()
def lookup(topic: str = "shipping") -> str:
"""Look up a topic in the knowledge base."""
return "Shipping takes 3 to 5 days."
server.run()

Then the agent, agent.py:

import asyncio
import shutil
import ctxflow_otel
from ctxflow_otel.mcp import child_env
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec
my_llm = ... # your function-calling LLM, for example OpenAI(model="gpt-4.1") from llama-index-llms-openai
async def main() -> None:
client = BasicMCPClient(
shutil.which("ctxflow-instrument") or "ctxflow-instrument",
args=["python", "server.py"], # your MCP server, started under ctxflow
env=child_env("kb-server"),
)
tools = await McpToolSpec(client=client).to_tool_list_async()
agent = FunctionAgent(tools=tools, llm=my_llm)
with ctxflow_otel.conversation("conv-1", user_id="u1", turn=0):
answer = await agent.run("How long does shipping take?")
print(answer)
asyncio.run(main())

Run the agent with ctxflow-instrument python agent.py. With an mcp 2.x server, one tool call produces three spans. LlamaIndex makes the tool span (agent side), the MCP SDK makes MCP send tools/call <tool> (client) and, in the server, tools/call <tool>. The server span carries the conversation and user of the turn, and with mcp 2.x it also carries the tool input and result. ctxflow shows them as one tool call. Details, versions and stdio: MCP servers and clients.

LLM spans come from the OpenInference instrumentation, so they work with any LlamaIndex LLM integration. Model, input tokens and output tokens reach the turn detail.

Google Gemini (llama-index-llms-google-genai) works. With an older SDK, the OpenInference handler failed on Gemini’s token details on every call: it logged AttributeError: 'list' object has no attribute 'get' and lost the counts after that line (reasoning, cache-read and thought tokens). ctxflow-otel now handles it (instrument_llamaindex() wraps the handler) and the log stays clean.