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.
pip install "ctxflow-otel[llamaindex]==0.2.2" # llama-index-core 0.14.19 or later, below 0.15OTEL_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.pyWhat 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 |
Start the instrumentation
Section titled “Start the instrumentation”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_otelfrom ctxflow_otel.llamaindex import instrument_llamaindex
provider = ctxflow_otel.init()instrument_llamaindex() # embedding text and vectors hidden, as under ctxflow-instrumentIt 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 exampleOPENINFERENCE_HIDE_INPUTS=true(this hides prompts too, so the turn detail shows no text). Underctxflow-instrumentyour ownLlamaIndexInstrumentor().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-instrumentlogs a WARNING that names it: Python SDK.
A complete example
Section titled “A complete example”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.)
import ctxflow_otelfrom llama_index.core import Document, Settings, VectorStoreIndexfrom 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 diskdoc = 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:
import ctxflow_otelfrom llama_index.core import Settings, StorageContext, load_index_from_storagefrom llama_index.core.embeddings import MockEmbeddingfrom 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?"))python build_index.pyctxflow-otel checkctxflow-instrument python app.pyRun 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.
Agents and workflows
Section titled “Agents and workflows”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_otelfrom fastapi import FastAPIfrom llama_index.core.agent.workflow import FunctionAgent
app = FastAPI() # run: ctxflow-instrument uvicorn app:appagent = 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 insideconversation(...)and readhandler.stream_events()outside the block. Do not keep the block open across ayield: Streaming and async generators. - The answer. ctxflow shows the
output.valueof the turn span as it is. For a workflow whose root span carries theStopEvent(...)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. Setoutput.valueyourself if you want a cleaner answer (Agent turns). - One turn per trace. One HTTP request, one question.
Retrievers and tools
Section titled “Retrievers and tools”- A LlamaIndex retriever or query engine already produces a retriever span with the documents, so you need no
retrievalspan of your own around it. If you add one anyway, ctxflow counts the retrieval once. - A tool that queries the vector store itself (a
FunctionToolthat callsvector_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).
Ingestion
Section titled “Ingestion”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.
Tools served over MCP
Section titled “Tools served over MCP”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 asyncioimport shutil
import ctxflow_otelfrom ctxflow_otel.mcp import child_envfrom llama_index.core.agent.workflow import FunctionAgentfrom 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.
Models and tokens
Section titled “Models and tokens”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.