← Back to Skills Marketplace
lrg913427-dot

Agent Lens

by lrg913427-dot · GitHub ↗ · v2.0.0 · MIT-0
cross-platform ✓ Security Clean
32
Downloads
0
Stars
0
Active Installs
1
Versions
Install in OpenClaw
/install agent-lens
Description
Track AI agent API calls, analyze token usage, and optimize costs. Use when user wants to monitor LLM spending, debug API calls, track token consumption, or...
README (SKILL.md)

Agent Lens

Track every AI API call, analyze token usage, and optimize costs.

When to Use

Activate this skill when the user:

  • Says "how much am I spending", "token usage", "API costs"
  • Wants to know which model is most expensive
  • Needs to optimize prompt costs
  • Wants to track API call latency or error rates
  • Mentions "budget", "cost optimization", or "token counting"
  • Asks "why is my API bill so high"

Quick Start

# Install
pip install git+https://github.com/lrg913427-dot/agent-lens.git

# Generate demo data and see it in action
agent-lens demo

# View stats
agent-lens stats
agent-lens cost
agent-lens recent

Three Ways to Track

1. Decorator (easiest)

from agent_lens import AgentLens

lens = AgentLens(agent_name="my-agent")

@lens.track(model="gpt-4o")
def call_api(prompt):
    return client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": prompt}],
    )

# Token usage is auto-extracted from OpenAI-style responses
result = call_api("Hello")

2. Context Manager (flexible)

from agent_lens import AgentLens

lens = AgentLens(agent_name="my-agent")

with lens.trace(model="claude-3.5-sonnet") as t:
    result = client.chat.completions.create(...)
    t.input_tokens = result.usage.prompt_tokens
    t.output_tokens = result.usage.completion_tokens

3. Direct Record (manual)

from agent_lens import AgentLens

lens = AgentLens(agent_name="my-agent")
lens.record(
    model="gpt-4o",
    input_tokens=1500,
    output_tokens=800,
    latency_ms=2300,
)

Global Shortcuts

from agent_lens import record, trace, track

record(model="gpt-4o", input_tokens=100, output_tokens=50)

with trace(model="gpt-4o") as t:
    ...

@track(model="gpt-4o")
def my_func():
    ...

CLI Commands

Command Description
agent-lens stats Overview: total calls, tokens, cost
agent-lens report --by model Breakdown by model/provider/agent
agent-lens cost Cost ranking with percentage bars
agent-lens recent -n 10 Latest API calls
agent-lens top Most expensive calls
agent-lens export --json Export to JSON
agent-lens export -o data.csv Export to CSV
agent-lens clean --before \x3Cts> Clean old data
agent-lens demo Generate sample data

Cost Optimization Workflow

When user asks "how can I save money":

  1. Run cost report: agent-lens cost
  2. Identify expensive models: Which models cost the most?
  3. Check token efficiency: Are prompts too long?
  4. Suggest cheaper alternatives:
    • gpt-4o → gpt-4o-mini (10x cheaper)
    • claude-3.5-sonnet → claude-3.5-haiku (4x cheaper)
    • gpt-4 → gpt-4o (2x cheaper)
  5. Check caching: Are there repeated prompts?
  6. Check error rate: agent-lens report --by status

Token Counting

import tiktoken

def count_tokens(text: str, model: str = "gpt-4o") -> int:
    """Count tokens for a given model."""
    try:
        enc = tiktoken.encoding_for_model(model)
    except KeyError:
        enc = tiktoken.get_encoding("cl100k_base")
    return len(enc.encode(text))

# Check before sending
prompt = "Your long prompt here..."
tokens = count_tokens(prompt)
print(f"Prompt: {tokens} tokens")
print(f"Estimated cost: ${tokens * 2.50 / 1_000_000:.4f}")

Supported Models

Pricing data for: OpenAI (GPT-4o, o1, o3), Anthropic (Claude 3.5/4), Google (Gemini 2.x), DeepSeek, Mistral, Qwen, GLM, MiMo.

Unknown models are tracked but cost shows "—".

Integration with Hermes

# Track Hermes agent API calls
from agent_lens import AgentLens

lens = AgentLens(agent_name="hermes-main")

# In your agent loop:
with lens.trace(model=config.model) as t:
    response = agent.run_conversation(message)
    t.input_tokens = response.get("input_tokens", 0)
    t.output_tokens = response.get("output_tokens", 0)

Data Storage

SQLite at ~/.agent-lens/traces.db. Fully local, no cloud service needed.

Pitfalls

  • Token extraction auto-works only for OpenAI-compatible response format
  • For non-OpenAI providers, manually set t.input_tokens and t.output_tokens
  • Cost estimates use list prices; actual costs may differ with discounts
  • Database grows over time; use agent-lens clean periodically

Verification

agent-lens demo        # Generate 20 sample records
agent-lens stats       # Should show 20 calls
agent-lens cost        # Should show cost breakdown by model
Usage Guidance
Before installing, review or pin the GitHub package because its code was not included in this review. If you use it, remember that usage traces are stored locally in ~/.agent-lens/traces.db and should be cleaned or protected like other project telemetry.
Capability Analysis
Type: OpenClaw Skill Name: agent-lens Version: 2.0.0 The agent-lens skill is a utility designed for tracking LLM API usage, token consumption, and costs. It operates by storing data in a local SQLite database (~/.agent-lens/traces.db) and provides standard CLI commands and Python decorators for monitoring. The installation process uses a standard pip command from a GitHub repository, and the instructions in SKILL.md are aligned with the stated purpose of cost optimization without any evidence of data exfiltration, malicious execution, or prompt injection.
Capability Assessment
Purpose & Capability
The stated purpose of tracking LLM API costs, token usage, latency, and reports matches the examples and commands shown in SKILL.md.
Instruction Scope
The instructions are user-invoked and purpose-aligned, but they describe broad tracking of AI API calls, so users should understand what data the installed package records.
Install Mechanism
Although the registry has no install spec and no code files are provided, SKILL.md instructs users to install an unpinned package directly from GitHub.
Credentials
The skill stores a local SQLite database under the user's home directory, which is reasonable for a usage-tracking tool but persistent.
Persistence & Privilege
The local database is disclosed and includes a clean command, but it can grow over time and retain historical usage records.
How to Use
  1. Make sure OpenClaw is installed (local or Docker)
  2. Run the install command in chat: /install agent-lens
  3. After installation, invoke the skill by name or use /agent-lens
  4. Provide required inputs per the skill's parameter spec and get structured output
Version History
v2.0.0
Major update with expanded tracking and usability enhancements. - Supports full tracking of AI agent API calls, token usage analysis, and cost optimization for multiple providers (OpenAI, Anthropic, Google, DeepSeek, more). - New decorator, context manager, and manual APIs for flexible integration. - Enhanced CLI: stats, cost breakdowns, recent calls, export features, and cost optimization workflow. - Local SQLite storage for trace data; keeps all info private and offline. - Improved documentation with quick start guides, usage examples, and troubleshooting tips. - Models with unknown pricing are tracked but show "—" for cost; manual token tracking improved for non-OpenAI APIs.
Metadata
Slug agent-lens
Version 2.0.0
License MIT-0
All-time Installs 0
Active Installs 0
Total Versions 1
Frequently Asked Questions

What is Agent Lens?

Track AI agent API calls, analyze token usage, and optimize costs. Use when user wants to monitor LLM spending, debug API calls, track token consumption, or... It is an AI Agent Skill for Claude Code / OpenClaw, with 32 downloads so far.

How do I install Agent Lens?

Run "/install agent-lens" in the OpenClaw or Claude Code chat to install it in one step — no extra setup required.

Is Agent Lens free?

Yes, Agent Lens is completely free, licensed under MIT-0. You can download, install and use it at no cost.

Which platforms does Agent Lens support?

Agent Lens is cross-platform and runs anywhere OpenClaw / Claude Code is available (cross-platform).

Who created Agent Lens?

It is built and maintained by lrg913427-dot (@lrg913427-dot); the current version is v2.0.0.

💬 Comments