← 返回 Skills 市场
lrg913427-dot

Agent Lens

作者 lrg913427-dot · GitHub ↗ · v2.1.0 · MIT-0
cross-platform ✓ 安全检测通过
45
总下载
0
收藏
0
当前安装
1
版本数
在 OpenClaw 中安装
/install gavin-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...
使用说明 (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
安全使用建议
This skill appears benign and purpose-aligned for LLM cost tracking. Before installing, review or pin the GitHub package because its code was not provided in the scan, and remember that usage traces are stored locally at ~/.agent-lens/traces.db until cleaned.
功能分析
Type: OpenClaw Skill Name: gavin-agent-lens Version: 2.1.0 The agent-lens skill is a utility for tracking LLM API usage, token counts, and costs locally using a SQLite database (~/.agent-lens/traces.db). The SKILL.md instructions are well-documented, providing clear guidance for the AI agent to monitor spending and optimize costs without any indicators of data exfiltration, unauthorized network calls, or malicious prompt injection.
能力评估
Purpose & Capability
The stated purpose—tracking LLM API calls, token usage, latency, errors, and costs—is coherent with the documented commands and Python instrumentation examples. This is observability data, so users should understand what is being recorded.
Instruction Scope
The instructions are user-directed examples and workflows for installing, recording, reporting, exporting, and cleaning Agent Lens data. They do not attempt to override user intent or force autonomous behavior.
Install Mechanism
The skill is instruction-only in the registry but tells users to install a package directly from GitHub. That is purpose-aligned, but the referenced package code was not included in the provided artifacts and is not pinned to a reviewed commit.
Credentials
No credentials or environment variables are declared. The documented runtime footprint is a local SQLite database under the user's home directory, which is proportionate for cost tracking but should be protected like usage records.
Persistence & Privilege
The skill discloses persistent local storage at ~/.agent-lens/traces.db and provides export/cleanup commands. This persistence is expected for historical reporting, but users should manage retention.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install gavin-agent-lens
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /gavin-agent-lens 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v2.1.0
- Enhanced documentation with detailed usage examples, quick start guide, and CLI command reference. - Expanded cost optimization workflow and troubleshooting sections. - Added sample code snippets for decorators, context managers, and manual token/cost tracking. - Listed supported model providers and described data storage practices. - Provided integration guidance for Hermes agent and clarified token counting recommendations.
元数据
Slug gavin-agent-lens
版本 2.1.0
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 1
常见问题

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... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 45 次。

如何安装 Agent Lens?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install gavin-agent-lens」即可一键安装,无需额外配置。

Agent Lens 是免费的吗?

是的,Agent Lens 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Agent Lens 支持哪些平台?

Agent Lens 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Agent Lens?

由 lrg913427-dot(@lrg913427-dot)开发并维护,当前版本 v2.1.0。

💬 留言讨论