Skip to content

docs(sample-app): add agent memory retrieval tracing example#4364

Open
FBISiri wants to merge 2 commits into
traceloop:mainfrom
FBISiri:docs/agent-memory-retrieval-tracing
Open

docs(sample-app): add agent memory retrieval tracing example#4364
FBISiri wants to merge 2 commits into
traceloop:mainfrom
FBISiri:docs/agent-memory-retrieval-tracing

Conversation

@FBISiri

@FBISiri FBISiri commented Jul 14, 2026

Copy link
Copy Markdown

Summary

Adds packages/sample-app/sample_app/agents/agent_memory_tracing_example.py — a self-contained, runnable example showing how to instrument memory read/write operations in an agent with OpenTelemetry spans.

Motivation

The existing sample apps cover LLM inference tracing (OpenAI, LangChain, Agno, CrewAI) and agent tool-call tracing, but none demonstrate how to trace the memory retrieval layer that is increasingly common in production agents. Teams that add Mem0, a custom vector store, or Redis for cross-session memory have no reference pattern for measuring retrieval latency and hit/miss rates alongside model inference.

What the example shows

agent.turn                          # parent span: full turn latency
  ├── memory.read                   # hit/miss + age_s attribute
  ├── llm.chat                      # model call (auto-traced by Traceloop)
  └── memory.write                  # stores new facts for future turns

Key span attributes:

Attribute Type Description
memory.operation string "read" or "write"
memory.key string lookup key
memory.hit bool present on read spans
memory.age_s float seconds since write, on hit only
memory.value_len int characters written
memory.context_injected bool whether retrieved memory shaped the prompt

The demo runs a two-turn warm session followed by a cold-start session so you can compare traces in the Traceloop dashboard.

Checklist

  • Single new file, no changes to existing code
  • No new dependencies (uses opentelemetry-api and traceloop-sdk already in sample-app requirements)
  • Runnable: python -m sample_app.agents.agent_memory_tracing_example (requires OPENAI_API_KEY)
  • Follows the same Traceloop.init() + tracer pattern as other sample-app examples

Summary by CodeRabbit

  • New Features
    • Added a runnable demo showing how an agent can retrieve and persist preferences across turns using tracing.
    • Demonstrates both memory carry-over within the same session and cold-start behavior in a new session.
    • Includes traced spans for memory read/write activity and chat completion calls, with sample output and tips for interpreting trace attributes.

Adds packages/sample-app/sample_app/agents/agent_memory_tracing_example.py —
a self-contained demo showing how to instrument memory read/write operations
in an agent with OpenTelemetry spans.

Key patterns demonstrated:
- memory.write span with key and value_len attributes
- memory.read span with hit/miss boolean and age_s on cache hits
- Parent agent.turn span correlating memory latency + LLM latency
- Two-session demo: warm memory hit vs cold-start miss

Useful for teams that add a retrieval-augmented memory layer (Mem0,
custom vector store, Redis) and want to measure retrieval quality
and latency separately from model inference in Traceloop.

No new dependencies — uses opentelemetry-api and traceloop-sdk already
present in the sample-app requirements.
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 56cf3f89-2350-4c93-a74c-73e3dfed1ca4

📥 Commits

Reviewing files that changed from the base of the PR and between 6282eef and a4ee856.

📒 Files selected for processing (1)
  • packages/sample-app/sample_app/agents/agent_memory_tracing_example.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/sample-app/sample_app/agents/agent_memory_tracing_example.py

📝 Walkthrough

Walkthrough

Adds a runnable OpenTelemetry/Traceloop example that traces session-scoped memory reads and writes around OpenAI agent turns, including hit/miss and age attributes, with a multi-session demo.

Changes

Agent memory tracing workflow

Layer / File(s) Summary
Traced memory store
packages/sample-app/sample_app/agents/agent_memory_tracing_example.py
Adds MemoryEntry and SimpleMemoryStore, with spans recording memory operation details, hit status, value length, and entry age.
Agent turn orchestration
packages/sample-app/sample_app/agents/agent_memory_tracing_example.py
Adds run_agent_turn, which reads session preferences, calls OpenAI under an llm.chat span, records response attributes, and conditionally stores new preferences.
Runnable demonstration
packages/sample-app/sample_app/agents/agent_memory_tracing_example.py
Adds initialization, a three-turn multi-session demo, printed tracing guidance, and the module entrypoint.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant run_agent_turn
  participant SimpleMemoryStore
  participant OpenAI
  User->>run_agent_turn: submit message and session ID
  run_agent_turn->>SimpleMemoryStore: read session preference
  run_agent_turn->>OpenAI: send system prompt and user message
  OpenAI-->>run_agent_turn: return completion
  run_agent_turn->>SimpleMemoryStore: store detected preference
  run_agent_turn-->>User: return agent response
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding an agent memory tracing example to the sample app.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/sample-app/sample_app/agents/agent_memory_tracing_example.py`:
- Around line 34-37: Update the Traceloop initialization in
agent-memory-tracing-example to configure a ConsoleSpanExporter, importing it
from opentelemetry.sdk.trace.export. Preserve the existing app_name and
disable_batch settings while adding the exporter for debugging spans and
hierarchy issues.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 474e3cbd-4206-414a-9016-8f4e457be2e1

📥 Commits

Reviewing files that changed from the base of the PR and between 93429cf and 6282eef.

📒 Files selected for processing (1)
  • packages/sample-app/sample_app/agents/agent_memory_tracing_example.py

Comment on lines +34 to +37
Traceloop.init(
app_name="agent-memory-tracing-demo",
disable_batch=True, # flush immediately so spans appear right away in dev
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Configure ConsoleSpanExporter for debugging.

The current initialization of Traceloop does not include a console exporter. As per coding guidelines, you must use ConsoleSpanExporter from opentelemetry.sdk.trace.export for debugging OpenTelemetry spans and hierarchy issues.

🛠️ Proposed fix to add the console exporter

Update the imports and initialization block to include the required exporter:

 from opentelemetry import trace
+from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
 from traceloop.sdk import Traceloop
 
 load_dotenv()
 
+traceloop_processor = Traceloop.get_default_span_processor(disable_batch=True)
+console_processor = SimpleSpanProcessor(ConsoleSpanExporter())
+
 Traceloop.init(
     app_name="agent-memory-tracing-demo",
-    disable_batch=True,  # flush immediately so spans appear right away in dev
+    processor=[traceloop_processor, console_processor],
 )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/sample-app/sample_app/agents/agent_memory_tracing_example.py` around
lines 34 - 37, Update the Traceloop initialization in
agent-memory-tracing-example to configure a ConsoleSpanExporter, importing it
from opentelemetry.sdk.trace.export. Preserve the existing app_name and
disable_batch settings while adding the exporter for debugging spans and
hierarchy issues.

Source: Coding guidelines

@FBISiri

FBISiri commented Jul 17, 2026

Copy link
Copy Markdown
Author

I have read the CLA Document and I hereby sign the CLA

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants