Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
fix(viewing-agent-context): extract system prompt from messages array (#10157)
Sarah Woodersbcdecf66b158
diff --git a/.skills/db-migrations-schema-changes/SKILL.md b/.skills/db-migrations-schema-changes/SKILL.mddeleted file mode 100644index fb74fe918..000000000--- a/.skills/db-migrations-schema-changes/SKILL.md+++ /dev/null@@ -1,141 +0,0 @@-----name: DB migrations and schema changes-description: >-- Workflows and commands for managing Alembic database migrations and schema changes- in the letta-cloud core app, including using uv, just, LETTA_PG_URI, and- switching between SQLite and Postgres.------# DB migrations and schema changes (letta-cloud core)--Use this skill whenever you need to change the database schema or debug Alembic-migrations in `apps/core` of the letta-cloud repo.--This skill assumes:-- Working directory: `apps/core`-- Migrations: Alembic in `apps/core/alembic`-- Python runner: `uv`-- Helper: `just ready` for environment + DB setup--## Quick start--1. Ensure environment is ready:- - `just ready`-2. For Postgres migrations, set:- - `export LETTA_PG_URI=postgresql+pg8000://postgres:postgres@localhost:5432/letta-core`-3. Make your ORM/schema change.-4. Autogenerate migration:- - `uv run alembic revision --autogenerate -m "<short_message>"`-5. Apply migration:- - `uv run alembic upgrade head`--See `references/migration-commands.md` for exact commands and variants.--## Standard workflows--### 1. Add or modify a column (ORM-first)--1. Identify the ORM model and table.-2. Update the SQLAlchemy model in `letta/orm/...`:- - Prefer using mixins (e.g. `ProjectMixin`) when available instead of- duplicating columns.-3. Run `just ready` if dependencies or environment may have changed.-4. Ensure `LETTA_PG_URI` is set if you want the migration to target Postgres.-5. Autogenerate Alembic revision with `uv`.-6. Inspect the generated file under `alembic/versions/`:- - Confirm `op.add_column` / `op.alter_column` match expectations.-7. Apply migrations with `uv run alembic upgrade head`.--Use this pattern for changes like adding `project_id` columns via `ProjectMixin`.--### 2. Data backfill / one-off data migration--1. Make sure the schema change (if any) is already represented in ORM + Alembic.-2. Create a new Alembic revision **without** autogenerate (or edit an- autogen file) and add Python logic in `upgrade()` that:- - Uses `op.get_bind()` and SQLAlchemy Core/SQL to backfill data.-3. Keep `downgrade()` simple and safe (ideally reversible).-4. Run against Postgres with `LETTA_PG_URI` set, using `uv run alembic upgrade head`.--### 3. Fixing a bad migration--Typical cases:-- Migration fails only on SQLite (ALTER constraint limitations).-- Migration was generated while pointing at SQLite instead of Postgres.--Workflow:-1. Identify the failing revision in `alembic/versions/`.-2. If failure is SQLite-specific, prefer running migrations against Postgres by- exporting `LETTA_PG_URI` and re-running upgrade.-3. If logic is wrong, create a **new** migration that fixes the problem rather- than editing an applied revision (especially in shared environments).-4. For purely local/dev history, you can delete and regenerate migrations but- only if no one else depends on them.--See `references/sqlite-vs-postgres-gotchas.md` for SQLite-specific issues.--### 4. Switching between SQLite and Postgres--Alembic picks the engine based on `letta.settings.DatabaseChoice` and-environment variables.--General rules:-- For local dev stateful runs, `just ready` handles baseline migrations.-- For schema design and production-like migrations, prefer Postgres and set- `LETTA_PG_URI`.--Workflow for Postgres-targeted migration:-1. `export LETTA_PG_URI=postgresql+pg8000://postgres:postgres@localhost:5432/letta-core`-2. From `apps/core`:- - `uv run alembic upgrade head`- - `uv run alembic revision --autogenerate -m "..."`--### 5. Resetting local Postgres for clean migration generation--If your local Postgres database has drifted from main (e.g., applied migrations-that no longer exist, or has stale schema), you can reset it to generate a clean-migration.--From the repo root (`/Users/sarahwooders/repos/letta-cloud`):--```bash-# 1. Remove postgres data directory-rm -rf ./data/postgres--# 2. Stop the running postgres container-docker stop $(docker ps -q --filter ancestor=ankane/pgvector)--# 3. Restart services (creates fresh postgres)-just start-services--# 4. Wait a moment for postgres to be ready, then apply all migrations-cd apps/core-export LETTA_PG_URI=postgresql+pg8000://postgres:postgres@localhost:5432/letta-core-uv run alembic upgrade head--# 5. Now generate your new migration-uv run alembic revision --autogenerate -m "your migration message"-```--This ensures the migration is generated against a clean database state matching-main, avoiding spurious diffs from local-only schema changes.--## Troubleshooting--- **"Target database is not up to date" when autogenerating**- - First run `uv run alembic upgrade head` (with appropriate engine/URI).-- **SQLite NotImplementedError about ALTER CONSTRAINT**- - Switch to Postgres by setting `LETTA_PG_URI` and rerun.-- **Autogenerated migration missing expected changes**- - Ensure ORM imports and metadata (`Base.metadata`) are correct and that the- changed model is imported in Alembic env context.-- **Autogenerated migration has unexpected drops/renames**- - Review model changes; consider explicit operations instead of relying on- autogenerate. Reset local Postgres (see workflow 5) to get a clean baseline.--## References--- `references/migration-commands.md` — canonical commands for `uv`, Alembic,- and `just`.-- `references/sqlite-vs-postgres-gotchas.md` — engine-specific pitfalls and- how to avoid them.diff --git a/.skills/db-migrations-schema-changes/references/migration-commands.md b/.skills/db-migrations-schema-changes/references/migration-commands.mddeleted file mode 100644index 24204a626..000000000--- a/.skills/db-migrations-schema-changes/references/migration-commands.md+++ /dev/null@@ -1,72 +0,0 @@-# Migration commands (letta-cloud core)--Working directory for all commands: `apps/core`.--## Environment setup--- One-shot environment + DB setup:- - `just ready`--## Postgres connection--Set the Postgres URI (adjust as needed for your env):--```bash-export LETTA_PG_URI=postgresql+pg8000://postgres:postgres@localhost:5432/letta-core-```--Alembic will log the effective URL (e.g. `Using database: postgresql+pg8000://...`).--## Alembic basics (with uv)--- Upgrade to latest:--```bash-uv run alembic upgrade head-```--- Downgrade one step:--```bash-uv run alembic downgrade -1-```--- Downgrade to a specific revision:--```bash-uv run alembic downgrade <revision_id>-```--- Generate new revision (autogenerate):--```bash-uv run alembic revision --autogenerate -m "short_message"-```--- Generate empty revision (manual operations):--```bash-uv run alembic revision -m "manual_migration"-```--## Typical workflow snippets--### Add/modify column--```bash-cd apps/core-just ready # optional but recommended-export LETTA_PG_URI=postgresql+pg8000://postgres:postgres@localhost:5432/letta-core-uv run alembic upgrade head # ensure DB is up to date-uv run alembic revision --autogenerate -m "add_<column>_to_<table>"-uv run alembic upgrade head-```--### Re-run last migration after edit (local only)--```bash-cd apps/core-export LETTA_PG_URI=postgresql+pg8000://postgres:postgres@localhost:5432/letta-core-uv run alembic downgrade -1-uv run alembic upgrade head-```diff --git a/.skills/db-migrations-schema-changes/references/sqlite-vs-postgres-gotchas.md b/.skills/db-migrations-schema-changes/references/sqlite-vs-postgres-gotchas.mddeleted file mode 100644index ea81cdd80..000000000--- a/.skills/db-migrations-schema-changes/references/sqlite-vs-postgres-gotchas.md+++ /dev/null@@ -1,41 +0,0 @@-# SQLite vs Postgres gotchas (letta-cloud core)--## SQLite limitations--SQLite has limited support for `ALTER TABLE`, especially around constraints and-foreign keys. In Alembic this often shows up as:--- `NotImplementedError: No support for ALTER of constraints in SQLite dialect...`--In `apps/core`, you may hit this when running migrations against SQLite that-drop or change foreign keys or constraints.--### How to handle--- Prefer running schema-changing migrations against Postgres by setting- `LETTA_PG_URI` and using:-- ```bash- uv run alembic upgrade head- ```--- If you must support SQLite, use Alembic batch mode patterns, but for this- project most complex migrations should target Postgres.--## Autogenerate differences--Running `alembic revision --autogenerate` against SQLite vs Postgres can-produce different diffs (especially around indexes and constraints).--Recommendations:--- For production/real migrations, always autogenerate against Postgres.-- If you see lots of unexpected index drops/adds, confirm which engine the- migration is inspecting and rerun with Postgres.--## Engine selection reminder--- Engine is controlled by `letta.settings.DatabaseChoice` and environment- (notably `LETTA_PG_URI`).-- `just ready` will also run migrations; ensure your desired engine is set- before relying on its database steps.diff --git a/.skills/llm-provider-usage-statistics/SKILL.md b/.skills/llm-provider-usage-statistics/SKILL.mddeleted file mode 100644index ff06467c9..000000000--- a/.skills/llm-provider-usage-statistics/SKILL.md+++ /dev/null@@ -1,43 +0,0 @@-----name: llm-provider-usage-statistics-description: Reference guide for token counting and prefix caching across LLM providers (OpenAI, Anthropic, Gemini). Use when debugging token counts or optimizing prefix caching.------# LLM Provider Usage Statistics--Reference documentation for how different LLM providers report token usage.--## Quick Reference: Token Counting Semantics--| Provider | `input_tokens` meaning | Cache tokens | Must add cache to get total? |-|----------|------------------------|--------------|------------------------------|-| OpenAI | TOTAL (includes cached) | `cached_tokens` is subset | No |-| Anthropic | NON-cached only | `cache_read_input_tokens` + `cache_creation_input_tokens` | **Yes** |-| Gemini | TOTAL (includes cached) | `cached_content_token_count` is subset | No |--**Critical difference:** Anthropic's `input_tokens` excludes cached tokens, so you must add them:-```-total_input = input_tokens + cache_read_input_tokens + cache_creation_input_tokens-```--## Quick Reference: Prefix Caching--| Provider | Min tokens | How to enable | TTL |-|----------|-----------|---------------|-----|-| OpenAI | 1,024 | Automatic | ~5-10 min |-| Anthropic | 1,024 | Requires `cache_control` breakpoints | 5 min |-| Gemini 2.0+ | 1,024 | Automatic (implicit) | Variable |--## Quick Reference: Reasoning/Thinking Tokens--| Provider | Field name | Models |-|----------|-----------|--------|-| OpenAI | `reasoning_tokens` | o1, o3 models |-| Anthropic | N/A | (thinking is in content blocks, not usage) |-| Gemini | `thoughts_token_count` | Gemini 2.0 with thinking enabled |--## Provider Reference Files--- **OpenAI:** [references/openai.md](references/openai.md) - Chat Completions vs Responses API, reasoning models, cached_tokens-- **Anthropic:** [references/anthropic.md](references/anthropic.md) - cache_control setup, beta headers, cache token fields-- **Gemini:** [references/gemini.md](references/gemini.md) - implicit caching, thinking tokens, usage_metadata fieldsdiff --git a/.skills/llm-provider-usage-statistics/references/anthropic.md b/.skills/llm-provider-usage-statistics/references/anthropic.mddeleted file mode 100644index 7dfdd6fb3..000000000--- a/.skills/llm-provider-usage-statistics/references/anthropic.md+++ /dev/null@@ -1,83 +0,0 @@-# Anthropic Usage Statistics--## Response Format--```-response.usage.input_tokens # NON-cached input tokens only-response.usage.output_tokens # Output tokens-response.usage.cache_read_input_tokens # Tokens read from cache-response.usage.cache_creation_input_tokens # Tokens written to cache-```--## Critical: Token Calculation--**Anthropic's `input_tokens` is NOT the total.** To get total input tokens:--```python-total_input = input_tokens + cache_read_input_tokens + cache_creation_input_tokens-```--This is different from OpenAI/Gemini where `prompt_tokens` is already the total.--## Prefix Caching (Prompt Caching)--**Requirements:**-- Minimum 1,024 tokens for Claude 3.5 Haiku/Sonnet-- Minimum 2,048 tokens for Claude 3 Opus-- Requires explicit `cache_control` breakpoints in messages-- TTL: 5 minutes--**How to enable:**-Add `cache_control` to message content:-```python-{- "role": "user",- "content": [- {- "type": "text",- "text": "...",- "cache_control": {"type": "ephemeral"}- }- ]-}-```--**Beta header required:**-```python-betas = ["prompt-caching-2024-07-31"]-```--## Cache Behavior--- `cache_creation_input_tokens`: Tokens that were cached on this request (cache write)-- `cache_read_input_tokens`: Tokens that were read from existing cache (cache hit)-- On first request: expect `cache_creation_input_tokens > 0`-- On subsequent requests with same prefix: expect `cache_read_input_tokens > 0`--## Streaming--In streaming mode, usage is reported in two events:--1. **`message_start`**: Initial usage (may have cache info)- ```python- event.message.usage.input_tokens- event.message.usage.output_tokens- event.message.usage.cache_read_input_tokens- event.message.usage.cache_creation_input_tokens- ```--2. **`message_delta`**: Cumulative output tokens- ```python- event.usage.output_tokens # This is CUMULATIVE, not incremental- ```--**Important:** Per Anthropic docs, `message_delta` token counts are cumulative, so assign (don't accumulate).--## Letta Implementation--- **Client:** `letta/llm_api/anthropic_client.py`-- **Streaming interfaces:**- - `letta/interfaces/anthropic_streaming_interface.py`- - `letta/interfaces/anthropic_parallel_tool_call_streaming_interface.py` (tracks cache tokens)-- **Extract method:** `AnthropicClient.extract_usage_statistics()`-- **Cache control:** `_add_cache_control_to_system_message()`, `_add_cache_control_to_messages()`diff --git a/.skills/llm-provider-usage-statistics/references/gemini.md b/.skills/llm-provider-usage-statistics/references/gemini.mddeleted file mode 100644index 2df708f5f..000000000--- a/.skills/llm-provider-usage-statistics/references/gemini.md+++ /dev/null@@ -1,81 +0,0 @@-# Gemini Usage Statistics--## Response Format--Gemini returns usage in `usage_metadata`:--```-response.usage_metadata.prompt_token_count # Total input tokens-response.usage_metadata.candidates_token_count # Output tokens-response.usage_metadata.total_token_count # Sum-response.usage_metadata.cached_content_token_count # Tokens from cache (optional)-response.usage_metadata.thoughts_token_count # Reasoning tokens (optional)-```--## Token Counting--- `prompt_token_count` is the TOTAL (includes cached)-- `cached_content_token_count` is a subset (when present)-- Similar to OpenAI's semantics--## Implicit Caching (Gemini 2.0+)--**Requirements:**-- Minimum 1,024 tokens-- Automatic (no opt-in required)-- Available on Gemini 2.0 Flash and later models--**Behavior:**-- Caching is probabilistic and server-side-- `cached_content_token_count` may or may not be present-- When present, indicates tokens that were served from cache--**Note:** Unlike Anthropic, Gemini doesn't have explicit cache_control. Caching is implicit and managed by Google's infrastructure.--## Reasoning/Thinking Tokens--For models with extended thinking (like Gemini 2.0 with thinking enabled):-- `thoughts_token_count` reports tokens used for reasoning-- These are similar to OpenAI's `reasoning_tokens`--**Enabling thinking:**-```python-generation_config = {- "thinking_config": {- "thinking_budget": 1024 # Max thinking tokens- }-}-```--## Streaming--In streaming mode:-- `usage_metadata` is typically in the **final chunk**-- Same fields as non-streaming-- May not be present in intermediate chunks--**Important:** `stream_async()` returns an async generator (not awaitable):-```python-# Correct:-stream = client.stream_async(request_data, llm_config)-async for chunk in stream:- ...--# Incorrect (will error):-stream = await client.stream_async(...) # TypeError!-```--## APIs--Gemini has two APIs:-- **Google AI (google_ai):** Uses `google.genai` SDK-- **Vertex AI (google_vertex):** Uses same SDK with different auth--Both share the same response format.--## Letta Implementation--- **Client:** `letta/llm_api/google_vertex_client.py` (handles both google_ai and google_vertex)-- **Streaming interface:** `letta/interfaces/gemini_streaming_interface.py`-- **Extract method:** `GoogleVertexClient.extract_usage_statistics()`-- Response is a `GenerateContentResponse` object with `.usage_metadata` attributediff --git a/.skills/llm-provider-usage-statistics/references/openai.md b/.skills/llm-provider-usage-statistics/references/openai.mddeleted file mode 100644index 259137914..000000000--- a/.skills/llm-provider-usage-statistics/references/openai.md+++ /dev/null@@ -1,61 +0,0 @@-# OpenAI Usage Statistics--## APIs and Response Formats--OpenAI has two APIs with different response structures:--### Chat Completions API-```-response.usage.prompt_tokens # Total input tokens (includes cached)-response.usage.completion_tokens # Output tokens-response.usage.total_tokens # Sum-response.usage.prompt_tokens_details.cached_tokens # Subset that was cached-response.usage.completion_tokens_details.reasoning_tokens # For o1/o3 models-```--### Responses API (newer)-```-response.usage.input_tokens # Total input tokens-response.usage.output_tokens # Output tokens-response.usage.total_tokens # Sum-response.usage.input_tokens_details.cached_tokens # Subset that was cached-response.usage.output_tokens_details.reasoning_tokens # For reasoning models-```--## Prefix Caching--**Requirements:**-- Minimum 1,024 tokens in the prefix-- Automatic (no opt-in required)-- Cached in 128-token increments-- TTL: approximately 5-10 minutes of inactivity--**Supported models:** GPT-4o, GPT-4o-mini, o1, o1-mini, o3-mini--**Cache behavior:**-- `cached_tokens` will be a multiple of 128-- Cache hit means those tokens were not re-processed-- Cost: cached tokens are cheaper than non-cached--## Reasoning Models (o1, o3)--For reasoning models, additional tokens are used for "thinking":-- `reasoning_tokens` in `completion_tokens_details`-- These are output tokens used for internal reasoning-- Not visible in the response content--## Streaming--In streaming mode, usage is reported in the **final chunk** when `stream_options.include_usage=True`:-```python-request_data["stream_options"] = {"include_usage": True}-```--The final chunk will have `chunk.usage` with the same structure as non-streaming.--## Letta Implementation--- **Client:** `letta/llm_api/openai_client.py`-- **Streaming interface:** `letta/interfaces/openai_streaming_interface.py`-- **Extract method:** `OpenAIClient.extract_usage_statistics()`-- Uses OpenAI SDK's pydantic models (`ChatCompletion`) for type-safe parsingdiff --git a/.skills/viewing-agent-context/SKILL.md b/.skills/viewing-agent-context/SKILL.mddeleted file mode 100644index 16cfddf3b..000000000--- a/.skills/viewing-agent-context/SKILL.md+++ /dev/null@@ -1,91 +0,0 @@-----name: viewing-agent-context-description: Explains what is inside an agent context window by fetching preview-raw-payload (live) or ClickHouse llm_traces (historical). Renders a human-readable HTML report (system prompt, messages, tools, model settings). Use when users ask what the model actually receives, want to inspect context composition, or want to inspect a past step's payload.------# Viewing Agent Context--Two modes:--1. **Live mode** (`--agent-id`): Fetch the current preview payload via `POST /v1/agents/{agent_id}/messages/preview-raw-payload`-2. **Historical mode** (`--step-id`): Fetch a past LLM request/response from ClickHouse `otel.llm_traces`--## When to use--Use this skill when a human asks:--- "What is in this agent's context window?"-- "Show me the real prompt/messages sent to the model"-- "Can I see dry-run context?"-- "Show me what was sent to the model for step X"-- "Inspect a past LLM call"--## Live mode: self-hosted server--```bash-python3 scripts/viewing_agent_context.py \- --agent-id <agent-id> \- --server-url "http://127.0.0.1:8283" \- --input "show me the exact context payload" \- --max-steps 1 \- --out ~/.letta/viewers/viewing-agent-context-<agent-id>.html-```--If your self-hosted server requires auth, add:--```bash---api-key "$LETTA_API_KEY"-```--## Live mode: api.letta.com--```bash-python3 scripts/viewing_agent_context.py \- --agent-id <agent-id> \- --server-url "https://api.letta.com" \- --api-key "$LETTA_API_KEY" \- --input "show me the exact context payload" \- --max-steps 1 \- --out ~/.letta/viewers/viewing-agent-context-<agent-id>.html-```--## Historical mode: inspect a past step--Query ClickHouse for a step's full request/response payload. Requires ClickHouse credentials via `--env-file` or env vars (`CLICKHOUSE_URL`, `CLICKHOUSE_USER`, `CLICKHOUSE_PASSWORD`).--```bash-python3 scripts/viewing_agent_context.py \- --step-id <step-id> \- --env-file /path/to/.env \- --out ~/.letta/viewers/viewing-step-context-<step-id>.html-```--The historical HTML report includes trace metadata (agent, model, provider, call type, timestamp), token usage stats, the full request payload (system prompt, messages, tools), and the full response payload.--## Args--| Arg | Description |-|-----|-------------|-| `--agent-id` | Live mode: agent to preview (mutually exclusive with `--step-id`) |-| `--step-id` | Historical mode: step to fetch from ClickHouse (mutually exclusive with `--agent-id`) |-| `--env-file` | Path to `.env` with ClickHouse credentials (historical mode) |-| `--server-url` | Letta server URL (live mode, default: `http://127.0.0.1:8283`) |-| `--api-key` | Bearer token (live mode, required for `api.letta.com`) |-| `--input` | Preview input text (live mode) |-| `--max-steps` | Preview max steps (live mode, default: 1) |-| `--timeout` | Request timeout in seconds (default: 45) |-| `--out` | Output HTML path |--## Output--The HTML includes:--1. Request settings (model, token params, reasoning/thinking flags)-2. Agent/trace metadata (tags, compaction settings, model settings — or trace metadata for historical)-3. System prompt section-4. Messages section (including system-reminder badge and newline-preserving user text rendering)-5. Tools/functions section (if present)-6. Response payload (historical mode only)-7. Full raw JSON payloads--Always return the absolute output file path so the user can open it directly in a browser.diff --git a/.skills/viewing-agent-context/scripts/viewing_agent_context.py b/.skills/viewing-agent-context/scripts/viewing_agent_context.pydeleted file mode 100755index b1a92464c..000000000--- a/.skills/viewing-agent-context/scripts/viewing_agent_context.py+++ /dev/null@@ -1,770 +0,0 @@-#!/usr/bin/env python3-from __future__ import annotations--import argparse-import html-import json-import os-import sys-from datetime import datetime, timezone-from pathlib import Path-from typing import Any, Dict, List, Optional, Tuple-from urllib.error import HTTPError, URLError-from urllib.parse import urlparse-from urllib.request import Request, urlopen---def get_json(url: str, headers: Dict[str, str], timeout: float) -> Tuple[Optional[Any], Optional[str]]:- req = Request(url, method="GET", headers=headers)- try:- with urlopen(req, timeout=timeout) as resp:- txt = resp.read().decode("utf-8", errors="replace")- return (json.loads(txt) if txt else None), None- except HTTPError as e:- detail = e.read().decode("utf-8", errors="replace") if hasattr(e, "read") else str(e)- return None, f"HTTP {e.code}: {detail[:2000]}"- except URLError as e:- return None, f"URL error: {e}"- except Exception as e:- return None, f"Unexpected error: {e}"---def post_json(url: str, headers: Dict[str, str], payload: Dict[str, Any], timeout: float) -> Tuple[Optional[Any], Optional[str]]:- body = json.dumps(payload).encode("utf-8")- req = Request(url, data=body, method="POST", headers={**headers, "Content-Type": "application/json"})- try:- with urlopen(req, timeout=timeout) as resp:- txt = resp.read().decode("utf-8", errors="replace")- return (json.loads(txt) if txt else None), None- except HTTPError as e:- detail = e.read().decode("utf-8", errors="replace") if hasattr(e, "read") else str(e)- return None, f"HTTP {e.code}: {detail[:2000]}"- except URLError as e:- return None, f"URL error: {e}"- except Exception as e:- return None, f"Unexpected error: {e}"---# ----------------------------------------------------------------------------# ClickHouse helpers-# ------------------------------------------------------------------------------def _parse_ch_url(raw_url: str) -> Tuple[str, int, bool]:- """Return (host, port, secure) from a ClickHouse URL."""- if "://" not in raw_url:- raw_url = f"http://{raw_url}"- parsed = urlparse(raw_url)- host = parsed.hostname- if not host:- raise ValueError(f"Invalid CLICKHOUSE_URL: {raw_url}")- secure = parsed.scheme == "https"- port = parsed.port if parsed.port is not None else (8443 if secure else 8123)- return host, port, secure---def _load_ch_credentials(env_file: Optional[str]) -> Tuple[str, str, str]:- """Load ClickHouse credentials from env file (preferred) then env vars.-- Uses dotenv_values() to avoid shell expansion of $ characters in passwords.- """- from dotenv import dotenv_values-- file_vals: Dict[str, Optional[str]] = {}- if env_file:- file_vals = dotenv_values(env_file)-- url = (file_vals.get("CLICKHOUSE_URL") or os.getenv("CLICKHOUSE_URL") or "").strip()- user = (file_vals.get("CLICKHOUSE_USER") or os.getenv("CLICKHOUSE_USER") or "").strip()- # Password: prefer dotenv_values first (avoids shell $ expansion), then env- password = (file_vals.get("CLICKHOUSE_PASSWORD") or os.getenv("CLICKHOUSE_PASSWORD") or "").strip()-- if not url:- raise ValueError("CLICKHOUSE_URL not found (check --env-file or env vars)")- if not user:- raise ValueError("CLICKHOUSE_USER not found (check --env-file or env vars)")- if not password:- raise ValueError("CLICKHOUSE_PASSWORD not found (check --env-file or env vars)")-- return url, user, password---def query_step_from_clickhouse(step_id: str, env_file: Optional[str]) -> Dict[str, Any]:- """Query otel.llm_traces for a step_id and return trace data."""- import clickhouse_connect-- url, user, password = _load_ch_credentials(env_file)- host, port, secure = _parse_ch_url(url)-- client = clickhouse_connect.get_client(- host=host,- port=port,- username=user,- password=password,- secure=secure,- )-- sql = """- SELECT- step_id,- agent_id,- organization_id,- run_id,- model,- provider,- call_type,- is_byok,- prompt_tokens,- completion_tokens,- total_tokens,- cached_input_tokens,- cache_write_tokens,- reasoning_tokens,- latency_ms,- request_size_bytes,- response_size_bytes,- is_error,- error_type,- error_message,- request_json,- response_json,- llm_config_json,- created_at- FROM otel.llm_traces- WHERE step_id = %(step_id)s- ORDER BY created_at DESC- LIMIT 1- """-- result = client.query(sql, parameters={"step_id": step_id})- if not result or not result.result_rows:- raise ValueError(f"No trace found for step_id={step_id}")-- row = result.result_rows[0]- columns = list(result.column_names)- return dict(zip(columns, row))---def _parse_json_str(value: Any) -> Dict[str, Any]:- """Parse a JSON string into a dict, handling edge cases."""- if not value:- return {}- if isinstance(value, dict):- return value- try:- parsed = json.loads(value)- return parsed if isinstance(parsed, dict) else {"_value": parsed}- except Exception:- return {"_raw": str(value)[:5000]}---# ----------------------------------------------------------------------------# HTML rendering helpers-# ------------------------------------------------------------------------------def esc_json(obj: Any) -> str:- return html.escape(json.dumps(obj, indent=2, ensure_ascii=False, default=str))---def extract_system_text(payload: Dict[str, Any]) -> str:- if isinstance(payload.get("instructions"), str):- return payload["instructions"]-- system = payload.get("system")- if isinstance(system, list):- parts: List[str] = []- for item in system:- if isinstance(item, dict) and isinstance(item.get("text"), str):- parts.append(item["text"])- if parts:- return "\n\n".join(parts)-- return "<missing>"---def extract_messages(payload: Dict[str, Any]) -> List[Any]:- if isinstance(payload.get("input"), list):- return payload["input"]- if isinstance(payload.get("messages"), list):- return payload["messages"]- return []---def extract_tools(payload: Dict[str, Any]) -> List[Any]:- if isinstance(payload.get("tools"), list):- return payload["tools"]- if isinstance(payload.get("functions"), list):- return payload["functions"]- return []---def _iter_strings(value: Any):- if isinstance(value, str):- yield value- elif isinstance(value, list):- for item in value:- yield from _iter_strings(item)- elif isinstance(value, dict):- for v in value.values():- yield from _iter_strings(v)---def has_system_reminder_in_content(message: Dict[str, Any]) -> bool:- content = message.get("content")- if content is None:- return False- needle = "<system-reminder>"- return any(needle in s.lower() for s in _iter_strings(content))---def _extract_text_blocks(content: Any) -> List[str]:- """Extract ordered human-readable text blocks from structured content arrays.-- Preview payloads often encode message content as a list of typed blocks, e.g.:- [{"type": "text", "text": "..."}, ...]- [{"type": "input_text", "text": "..."}, ...]-- This helper preserves that order and returns plain text blocks so we can render- them cleanly instead of dumping JSON.- """- blocks: List[str] = []- if not isinstance(content, list):- return blocks-- for item in content:- if isinstance(item, str):- blocks.append(item)- continue-- if not isinstance(item, dict):- continue-- # Primary shape: {"type": "text"|"input_text"|..., "text": "..."}- text_value = item.get("text")- if isinstance(text_value, str):- blocks.append(text_value)- continue-- # Secondary shape: nested content arrays/strings under "content"- nested = item.get("content")- if isinstance(nested, str):- blocks.append(nested)- elif isinstance(nested, list):- blocks.extend(_extract_text_blocks(nested))-- return blocks---def render_content_for_display(message: Dict[str, Any], msg_type: Optional[str]) -> str:- content = message.get("content")-- # Structured multi-part content (e.g. [{"type":"text","text":"..."}])- # should render as readable text blocks instead of JSON.- text_blocks = _extract_text_blocks(content)- if text_blocks:- return "\n\n".join(text_blocks)[:8000]-- if isinstance(content, str):- return content[:8000]-- if content is not None:- return json.dumps(content, ensure_ascii=False, default=str)[:8000]-- if msg_type == "function_call":- return json.dumps(- {- "call_id": message.get("call_id"),- "name": message.get("name"),- "arguments": message.get("arguments"),- "status": message.get("status"),- },- ensure_ascii=False,- default=str,- )[:8000]-- if msg_type == "function_call_output":- return json.dumps(- {- "call_id": message.get("call_id"),- "output": message.get("output"),- },- ensure_ascii=False,- default=str,- )[:8000]-- # Unknown shape: show full message object for inspection.- return json.dumps(message, ensure_ascii=False, default=str)[:8000]---def render_messages(messages: List[Any]) -> str:- if not messages:- return "<p class='muted'>No messages found.</p>"-- chunks = []- for i, m in enumerate(messages, 1):- if not isinstance(m, dict):- continue-- role = m.get("role")- msg_type = m.get("type")- has_system_reminder = has_system_reminder_in_content(m)-- # Preview payloads often include provider-specific tool call rows without `role`.- # Fall back to message `type` so we don't render these as "unknown".- label = str(role or msg_type or "unknown")-- parsed_preview = render_content_for_display(m, msg_type)-- chunks.append(- """- <details class='card'>- <summary>#{idx} <strong>{label}</strong>{system_reminder_tag}</summary>- <pre>{parsed}</pre>- <details>- <summary class='muted'>raw message object</summary>- <pre>{raw}</pre>- </details>- </details>- """.format(- idx=i,- label=html.escape(label),- system_reminder_tag=(" <span class='tag'>system reminder</span>" if has_system_reminder else ""),- parsed=html.escape(parsed_preview),- raw=esc_json(m),- )- )- return "\n".join(chunks) if chunks else "<p class='muted'>No message entries.</p>"---def render_tools(tools: List[Any]) -> str:- if not tools:- return "<p class='muted'>No tools/functions found in preview payload.</p>"- chunks = []- for i, t in enumerate(tools, 1):- if not isinstance(t, dict):- continue- name = t.get("name")- if not name and isinstance(t.get("function"), dict):- name = t["function"].get("name")- desc = t.get("description")- if not desc and isinstance(t.get("function"), dict):- desc = t["function"].get("description")- chunks.append(- f"<details class='card'><summary>#{i} <code>{html.escape(str(name or '<unknown>'))}</code> — {html.escape(str(desc or ''))}</summary><pre>{esc_json(t)}</pre></details>"- )- return "\n".join(chunks) if chunks else "<p class='muted'>No renderable tools found.</p>"---# ----------------------------------------------------------------------------# HTML builders-# -----------------------------------------------------------------------------_COMMON_STYLE = """- body { font-family: ui-sans-serif, system-ui; margin: 24px; background: #fafafa; color: #111; }- .panel { background: #fff; border: 1px solid #e5e5e5; border-radius: 10px; padding: 12px; margin-bottom: 12px; }- .card { background: #fff; border: 1px solid #e5e5e5; border-radius: 8px; padding: 8px 12px; margin-bottom: 8px; }- .warn { background: #fff3f3; border-color: #ffcbcb; }- .tag { margin-left: 8px; font-size: 12px; color: #6b21a8; background: #f3e8ff; border: 1px solid #e9d5ff; border-radius: 999px; padding: 1px 8px; font-weight: 600; }- .chip { display: inline-block; margin: 4px 6px 0 0; font-size: 12px; color: #1d4ed8; background: #dbeafe; border: 1px solid #bfdbfe; border-radius: 999px; padding: 2px 8px; font-weight: 600; }- pre { white-space: pre-wrap; word-break: break-word; background: #f5f5f5; padding: 10px; border-radius: 8px; }- .muted { color: #666; }- summary { cursor: pointer; }- nav a { margin-right: 10px; }- .kv-table { border-collapse: collapse; margin: 8px 0; }- .kv-table td { padding: 4px 12px 4px 0; vertical-align: top; }- .kv-table td:first-child { font-weight: 600; white-space: nowrap; color: #333; }-"""---def build_html(- agent_id: str,- preview_url: str,- agent_url: str,- payload: Dict[str, Any],- agent_payload: Dict[str, Any],- errors: List[str],-) -> str:- generated = datetime.now(timezone.utc).isoformat()- model = payload.get("model") if isinstance(payload, dict) else None- messages = extract_messages(payload) if isinstance(payload, dict) else []- system_text = extract_system_text(payload) if isinstance(payload, dict) else "<missing>"- tools = extract_tools(payload) if isinstance(payload, dict) else []-- tags = agent_payload.get("tags") if isinstance(agent_payload.get("tags"), list) else []- has_compaction_settings_key = "compaction_settings" in agent_payload- compaction_settings = agent_payload.get("compaction_settings")- has_model_settings_key = "model_settings" in agent_payload- model_settings = agent_payload.get("model_settings")-- settings = {- "model": model,- "max_tokens": payload.get("max_tokens") if isinstance(payload, dict) else None,- "temperature": payload.get("temperature") if isinstance(payload, dict) else None,- "thinking": payload.get("thinking") if isinstance(payload, dict) else None,- "reasoning": payload.get("reasoning") if isinstance(payload, dict) else None,- "output_config": payload.get("output_config") if isinstance(payload, dict) else None,- "message_count": len(messages) if isinstance(messages, list) else None,- "tool_count": len(tools) if isinstance(tools, list) else None,- "top_keys": list(payload.keys()) if isinstance(payload, dict) else None,- }-- warn_html = (- "<div class='panel warn'><strong>Warnings</strong><ul>" + "".join(f"<li>{html.escape(e)}</li>" for e in errors) + "</ul></div>"- if errors- else ""- )-- tags_html = "".join(f"<span class='chip'>{html.escape(str(t))}</span>" for t in tags)- if not tags_html:- tags_html = "<span class='muted'>No tags found.</span>"-- if has_compaction_settings_key:- compaction_html = esc_json(compaction_settings)- else:- compaction_html = "<span class='muted'>compaction_settings not present on agent payload.</span>"-- if has_model_settings_key:- model_settings_html = esc_json(model_settings)- else:- model_settings_html = "<span class='muted'>model_settings not present on agent payload.</span>"-- return f"""<!doctype html>-<html lang='en'>-<head>- <meta charset='utf-8'>- <meta name='viewport' content='width=device-width, initial-scale=1'>- <title>Viewing Agent Context — {html.escape(agent_id)}</title>- <style>{_COMMON_STYLE}</style>-</head>-<body>- <h1>Viewing Agent Context (Preview-Only)</h1>- <p class='muted'>Generated: {html.escape(generated)} | Agent: <code>{html.escape(agent_id)}</code></p>-- <div class='panel'>- <div><strong>Preview endpoint:</strong> <code>{html.escape(preview_url)}</code></div>- <div><strong>Agent endpoint:</strong> <code>{html.escape(agent_url)}</code></div>- </div>-- {warn_html}-- <nav class='panel'>- <a href='#settings'>Settings</a>- <a href='#agent'>Agent metadata</a>- <a href='#system'>System</a>- <a href='#messages'>Messages</a>- <a href='#tools'>Tools</a>- <a href='#raw'>Raw JSON</a>- </nav>-- <section id='settings' class='panel'>- <h2>Request Settings</h2>- <pre>{esc_json(settings)}</pre>- </section>-- <section id='agent' class='panel'>- <h2>Agent Metadata</h2>- <h3>Tags</h3>- <div>{tags_html}</div>- <h3 style='margin-top: 12px;'>Compaction Settings (<code>agent.compaction_settings</code>)</h3>- <pre>{compaction_html}</pre>- <h3 style='margin-top: 12px;'>Model Settings (<code>agent.model_settings</code>)</h3>- <pre>{model_settings_html}</pre>- </section>-- <section id='system' class='panel'>- <h2>System Prompt</h2>- <pre>{html.escape(system_text)}</pre>- </section>-- <section id='messages' class='panel'>- <h2>Messages</h2>- {render_messages(messages)}- </section>-- <section id='tools' class='panel'>- <h2>Tools / Functions</h2>- {render_tools(tools)}- </section>-- <section id='raw' class='panel'>- <h2>Full Preview Payload JSON</h2>- <pre>{esc_json(payload)}</pre>- <h2 style='margin-top: 16px;'>Full Agent JSON</h2>- <pre>{esc_json(agent_payload)}</pre>- </section>-</body>-</html>-"""---def build_step_html(- step_id: str,- trace_row: Dict[str, Any],- request_payload: Dict[str, Any],- response_payload: Dict[str, Any],- errors: List[str],-) -> str:- """Build HTML report for a historical step fetched from ClickHouse."""- generated = datetime.now(timezone.utc).isoformat()- model = request_payload.get("model") if isinstance(request_payload, dict) else None- messages = extract_messages(request_payload) if isinstance(request_payload, dict) else []- system_text = extract_system_text(request_payload) if isinstance(request_payload, dict) else "<missing>"- tools = extract_tools(request_payload) if isinstance(request_payload, dict) else []-- settings = {- "model": model or trace_row.get("model"),- "max_tokens": request_payload.get("max_tokens") if isinstance(request_payload, dict) else None,- "temperature": request_payload.get("temperature") if isinstance(request_payload, dict) else None,- "thinking": request_payload.get("thinking") if isinstance(request_payload, dict) else None,- "reasoning": request_payload.get("reasoning") if isinstance(request_payload, dict) else None,- "output_config": request_payload.get("output_config") if isinstance(request_payload, dict) else None,- "message_count": len(messages) if isinstance(messages, list) else None,- "tool_count": len(tools) if isinstance(tools, list) else None,- "top_keys": list(request_payload.keys()) if isinstance(request_payload, dict) else None,- }-- warn_html = (- "<div class='panel warn'><strong>Warnings</strong><ul>" + "".join(f"<li>{html.escape(e)}</li>" for e in errors) + "</ul></div>"- if errors- else ""- )-- # Trace metadata table- trace_meta = {- "step_id": trace_row.get("step_id", ""),- "agent_id": trace_row.get("agent_id", ""),- "organization_id": trace_row.get("organization_id", ""),- "run_id": trace_row.get("run_id", ""),- "model": trace_row.get("model", ""),- "provider": trace_row.get("provider", ""),- "call_type": trace_row.get("call_type", ""),- "is_byok": bool(trace_row.get("is_byok", False)),- "created_at": str(trace_row.get("created_at", "")),- }-- token_stats = {- "prompt_tokens": trace_row.get("prompt_tokens", 0),- "completion_tokens": trace_row.get("completion_tokens", 0),- "total_tokens": trace_row.get("total_tokens", 0),- "cached_input_tokens": trace_row.get("cached_input_tokens"),- "cache_write_tokens": trace_row.get("cache_write_tokens"),- "reasoning_tokens": trace_row.get("reasoning_tokens"),- "latency_ms": trace_row.get("latency_ms", 0),- "request_size_bytes": trace_row.get("request_size_bytes", 0),- "response_size_bytes": trace_row.get("response_size_bytes", 0),- }-- error_info = {}- if trace_row.get("is_error"):- error_info = {- "is_error": True,- "error_type": trace_row.get("error_type", ""),- "error_message": trace_row.get("error_message", ""),- }-- def _kv_table(d: Dict[str, Any]) -> str:- rows = []- for k, v in d.items():- val_str = html.escape(str(v)) if v is not None else "<span class='muted'>null</span>"- rows.append(f"<tr><td>{html.escape(str(k))}</td><td><code>{val_str}</code></td></tr>")- return "<table class='kv-table'>" + "".join(rows) + "</table>"-- error_section = ""- if error_info:- error_section = f"""- <section class='panel warn'>- <h2>Error</h2>- {_kv_table(error_info)}- </section>"""-- # LLM config from trace- llm_config_raw = trace_row.get("llm_config_json", "")- llm_config = _parse_json_str(llm_config_raw) if llm_config_raw else {}- llm_config_html = esc_json(llm_config) if llm_config else "<span class='muted'>No LLM config recorded.</span>"-- title_id = html.escape(step_id[:40])-- return f"""<!doctype html>-<html lang='en'>-<head>- <meta charset='utf-8'>- <meta name='viewport' content='width=device-width, initial-scale=1'>- <title>Viewing Step Context — {title_id}</title>- <style>{_COMMON_STYLE}</style>-</head>-<body>- <h1>Viewing Step Context (Historical — ClickHouse)</h1>- <p class='muted'>Generated: {html.escape(generated)} | Step: <code>{html.escape(step_id)}</code></p>-- {warn_html}-- <nav class='panel'>- <a href='#trace'>Trace metadata</a>- <a href='#tokens'>Token usage</a>- <a href='#settings'>Request settings</a>- <a href='#system'>System</a>- <a href='#messages'>Messages</a>- <a href='#tools'>Tools</a>- <a href='#response'>Response</a>- <a href='#raw'>Raw JSON</a>- </nav>-- <section id='trace' class='panel'>- <h2>Trace Metadata</h2>- {_kv_table(trace_meta)}- </section>-- <section id='tokens' class='panel'>- <h2>Token Usage</h2>- {_kv_table(token_stats)}- </section>- {error_section}-- <section id='settings' class='panel'>- <h2>Request Settings</h2>- <pre>{esc_json(settings)}</pre>- <h3 style='margin-top: 12px;'>LLM Config</h3>- <pre>{llm_config_html}</pre>- </section>-- <section id='system' class='panel'>- <h2>System Prompt</h2>- <pre>{html.escape(system_text)}</pre>- </section>-- <section id='messages' class='panel'>- <h2>Messages</h2>- {render_messages(messages)}- </section>-- <section id='tools' class='panel'>- <h2>Tools / Functions</h2>- {render_tools(tools)}- </section>-- <section id='response' class='panel'>- <h2>Response Payload</h2>- <pre>{esc_json(response_payload)}</pre>- </section>-- <section id='raw' class='panel'>- <h2>Full Request Payload JSON</h2>- <pre>{esc_json(request_payload)}</pre>- </section>-</body>-</html>-"""---# ----------------------------------------------------------------------------# CLI-# ------------------------------------------------------------------------------def main() -> int:- parser = argparse.ArgumentParser(- description="Generate a human-readable context report from preview-raw-payload (live) or ClickHouse llm_traces (historical)."- )-- # Mode selection: exactly one of --agent-id or --step-id- mode = parser.add_mutually_exclusive_group(required=True)- mode.add_argument("--agent-id", help="Live mode: fetch preview-raw-payload for this agent")- mode.add_argument("--step-id", help="Historical mode: fetch request/response from ClickHouse for this step_id")-- # Live-mode options- parser.add_argument("--server-url", default=os.getenv("LETTA_SERVER_URL") or "http://127.0.0.1:8283")- parser.add_argument("--api-key", default=os.getenv("LETTA_API_KEY"))- parser.add_argument("--input", default="show me the exact context payload")- parser.add_argument("--max-steps", type=int, default=1)-- # ClickHouse options- parser.add_argument("--env-file", help="Path to .env file with CLICKHOUSE_URL, CLICKHOUSE_USER, CLICKHOUSE_PASSWORD")-- # Common- parser.add_argument("--timeout", type=float, default=45.0)- parser.add_argument("--out", default=None)-- args = parser.parse_args()-- # ------------------------------------------------------------------------ # Historical mode (--step-id)- # ------------------------------------------------------------------------ if args.step_id:- errors: List[str] = []- try:- trace_row = query_step_from_clickhouse(args.step_id, args.env_file)- except Exception as e:- print(f"ClickHouse query failed: {e}", file=sys.stderr)- return 1-- request_payload = _parse_json_str(trace_row.get("request_json"))- response_payload = _parse_json_str(trace_row.get("response_json"))-- if not request_payload:- errors.append("request_json was empty or unparseable")- if not response_payload:- errors.append("response_json was empty or unparseable")-- out = Path(args.out).expanduser() if args.out else Path.home() / ".letta" / "viewers" / f"viewing-step-context-{args.step_id}.html"- out.parent.mkdir(parents=True, exist_ok=True)- out.write_text(- build_step_html(args.step_id, trace_row, request_payload, response_payload, errors),- encoding="utf-8",- )-- print(f"Generated: {out}")- if errors:- print("Warnings:")- for e in errors:- print(f" - {e}")- else:- print(f"Trace fetched successfully (model={trace_row.get('model')}, created_at={trace_row.get('created_at')}).")- return 0-- # ------------------------------------------------------------------------ # Live mode (--agent-id)- # ------------------------------------------------------------------------ server = args.server_url.rstrip("/")- preview_url = f"{server}/v1/agents/{args.agent_id}/messages/preview-raw-payload"- agent_url = f"{server}/v1/agents/{args.agent_id}"-- headers: Dict[str, str] = {- "Accept": "application/json",- "User-Agent": "letta-code-cli/viewing-agent-context",- }- if args.api_key:- headers["Authorization"] = f"Bearer {args.api_key}"-- errors = []-- payload, err = post_json(preview_url, headers, {"input": args.input, "max_steps": args.max_steps}, args.timeout)- if err:- errors.append(f"preview: {err}")-- agent_payload_raw, agent_err = get_json(agent_url, headers, args.timeout)- if agent_err:- errors.append(f"agent: {agent_err}")-- payload_dict = payload if isinstance(payload, dict) else ({"raw": payload} if payload is not None else {})- agent_payload = (- agent_payload_raw if isinstance(agent_payload_raw, dict) else ({"raw": agent_payload_raw} if agent_payload_raw is not None else {})- )-- out = Path(args.out).expanduser() if args.out else Path.home() / ".letta" / "viewers" / f"viewing-agent-context-{args.agent_id}.html"- out.parent.mkdir(parents=True, exist_ok=True)- out.write_text(build_html(args.agent_id, preview_url, agent_url, payload_dict, agent_payload, errors), encoding="utf-8")-- print(f"Generated: {out}")- if errors:- print("Warnings:")- for e in errors:- print(f" - {e}")- else:- print("Preview fetched successfully.")-- return 0---if __name__ == "__main__":- raise SystemExit(main())